We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 7f8f48a commit cd31b04Copy full SHA for cd31b04
462. Minimum Moves to Equal Array Elements II
@@ -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
21
22
23
24
25
+ //Calculate the steps by taking 2 pointers
26
+ int i = 0, j = nums.length-1;
27
28
+ while(i < j) {
29
+ steps += (nums[j]-nums[i]);
30
+ i++;
31
+ j--;
32
33
34
35
36
0 commit comments