The brute force approach involves checking every possible pair of elements in the array and calculating the difference between each pair. Keep track of the minimum difference encountered.
publicclassSolution {
publicintfindMinDifference(int[] nums) {
int minDifference = Integer.MAX_VALUE;
// Iterate through all pairs of elementsfor (int i = 0; i < nums.length- 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
int diff = Math.abs(nums[i]- nums[j]);
if (diff < minDifference) {
minDifference = diff;
}
}
}
return minDifference;
}
}
1
2
3
4
5
6
7
8
9
10
11
deffind_min_difference_brute_force(nums):
min_difference = float("inf")
# Iterate through all pairs of elementsfor i in range(len(nums) -1):
for j in range(i +1, len(nums)):
diff = abs(nums[i] - nums[j])
if diff < min_difference:
min_difference = diff
return min_difference
To find the minimum difference between any pair in an unsorted array, a straightforward approach is to leverage sorting:
Sort the Array: Sorting the array allows us to compare adjacent elements, which are naturally the closest in value.
Find Minimum Difference: Iterate through the sorted array and compute the difference between each pair of adjacent elements. Track the smallest difference encountered.
publicclassSolution {
publicintfindMinDifference(int[] nums) {
// Sort the array Arrays.sort(nums);
// Initialize minimum difference to a large valueint minDifference = Integer.MAX_VALUE;
// Iterate through sorted array and find the minimum differencefor (int i = 1; i < nums.length; i++) {
int diff = nums[i]- nums[i - 1];
if (diff < minDifference) {
minDifference = diff;
}
}
return minDifference;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
deffind_min_difference(nums):
# Sort the array nums.sort()
# Initialize minimum difference to a large value min_difference = float("inf")
# Iterate through sorted array and find the minimum differencefor i in range(1, len(nums)):
diff = nums[i] - nums[i -1]
if diff < min_difference:
min_difference = diff
return min_difference