|
2 | 2 |
|
3 | 3 | import java.util.Arrays;
|
4 | 4 |
|
5 |
| -/**462. Minimum Moves to Equal Array Elements II |
| 5 | +/** |
| 6 | + * 462. Minimum Moves to Equal Array Elements II |
| 7 | + * |
6 | 8 | * Given a non-empty integer array,
|
7 | 9 | * find the minimum number of moves required to make all array elements equal,
|
8 | 10 | * where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
|
9 |
| -
|
10 |
| - You may assume the array's length is at most 10,000. |
| 11 | + * |
| 12 | + * You may assume the array's length is at most 10,000. |
11 | 13 |
|
12 | 14 | Example:
|
13 | 15 |
|
|
20 | 22 | Explanation:
|
21 | 23 | Only two moves are needed (remember each move increments or decrements one element):
|
22 | 24 |
|
23 |
| - [1,2,3] => [2,2,3] => [2,2,2]*/ |
| 25 | + [1,2,3] => [2,2,3] => [2,2,2] |
| 26 | + */ |
24 | 27 |
|
25 | 28 | public class _462 {
|
26 | 29 |
|
27 |
| - public static int minMoves2(int[] nums) { |
28 |
| - /**sort this array, find the median of this array as the pivot*/ |
29 |
| - Arrays.sort(nums); |
30 |
| - int result = 0; |
31 |
| - int result1 = 0; |
32 |
| - if (nums.length % 2 != 0) { |
33 |
| - int median = nums[nums.length / 2]; |
34 |
| - for (int n : nums) { |
35 |
| - result += Math.abs(n - median); |
36 |
| - } |
37 |
| - return result; |
38 |
| - } else { |
39 |
| - int median1 = nums[nums.length / 2]; |
40 |
| - for (int n : nums) { |
41 |
| - result1 += Math.abs(n - median1); |
42 |
| - } |
43 |
| - int result2 = 0; |
44 |
| - int median2 = nums[nums.length / 2 - 1]; |
45 |
| - for (int n : nums) { |
46 |
| - result2 += Math.abs(n - median2); |
| 30 | + public static class Solution1 { |
| 31 | + public int minMoves2(int[] nums) { |
| 32 | + /**sort this array, find the median of this array as the pivot*/ |
| 33 | + Arrays.sort(nums); |
| 34 | + int result = 0; |
| 35 | + int result1 = 0; |
| 36 | + if (nums.length % 2 != 0) { |
| 37 | + int median = nums[nums.length / 2]; |
| 38 | + for (int n : nums) { |
| 39 | + result += Math.abs(n - median); |
| 40 | + } |
| 41 | + return result; |
| 42 | + } else { |
| 43 | + int median1 = nums[nums.length / 2]; |
| 44 | + for (int n : nums) { |
| 45 | + result1 += Math.abs(n - median1); |
| 46 | + } |
| 47 | + int result2 = 0; |
| 48 | + int median2 = nums[nums.length / 2 - 1]; |
| 49 | + for (int n : nums) { |
| 50 | + result2 += Math.abs(n - median2); |
| 51 | + } |
| 52 | + result1 = Math.min(result1, result2); |
| 53 | + return result1; |
47 | 54 | }
|
48 |
| - result1 = Math.min(result1, result2); |
49 |
| - return result1; |
50 | 55 | }
|
51 |
| - |
52 |
| - } |
53 |
| - |
54 |
| - public static void main(String... args) { |
55 |
| - int[] nums = new int[]{1, 2, 3}; |
56 |
| - System.out.println(minMoves2(nums)); |
57 | 56 | }
|
58 | 57 |
|
59 | 58 | }
|
0 commit comments