Skip to content

Commit cd31b04

Browse files
authored
Create 462. Minimum Moves to Equal Array Elements II
1 parent 7f8f48a commit cd31b04

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public int minMoves2(int[] nums) {
3+
int n = nums.length;
4+
//Sort the array
5+
Arrays.sort(nums);
6+
7+
//Find the median
8+
int median = n%2==0 ? (nums[n/2]+nums[n/2-1])/2 : nums[n/2];
9+
int steps = 0;
10+
11+
//Calculate steps
12+
for(int num : nums) {
13+
steps += Math.abs(num-median);
14+
}
15+
16+
return steps;
17+
}
18+
}
19+
20+
class Solution {
21+
public int minMoves2(int[] nums) {
22+
//Sort the array
23+
Arrays.sort(nums);
24+
25+
//Calculate the steps by taking 2 pointers
26+
int i = 0, j = nums.length-1;
27+
int steps = 0;
28+
while(i < j) {
29+
steps += (nums[j]-nums[i]);
30+
i++;
31+
j--;
32+
}
33+
34+
return steps;
35+
}
36+
}

0 commit comments

Comments
 (0)