File tree 2 files changed +39
-0
lines changed
2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ public class MinimumMovestoEqualArrayElementsII {
6
+
7
+ public static int minMoves2 (int [] nums ) {
8
+ /**sort this array, find the median of this array as the pivot*/
9
+ Arrays .sort (nums );
10
+ int result = 0 , result1 = 0 ;
11
+ if (nums .length %2 != 0 ) {
12
+ int median = nums [nums .length /2 ];
13
+ for ( int n : nums ) {
14
+ result += Math .abs (n - median );
15
+ }
16
+ return result ;
17
+ } else {
18
+ int median1 = nums [nums .length /2 ];
19
+ for ( int n : nums ) {
20
+ result1 += Math .abs (n - median1 );
21
+ }
22
+ int result2 = 0 ;
23
+ int median2 = nums [nums .length /2 -1 ];
24
+ for ( int n : nums ) {
25
+ result2 += Math .abs (n - median2 );
26
+ }
27
+ result1 = Math .min (result1 , result2 );
28
+ return result1 ;
29
+ }
30
+
31
+ }
32
+
33
+ public static void main (String ...args ){
34
+ int [] nums = new int []{1 ,2 ,3 };
35
+ System .out .println (minMoves2 (nums ));
36
+ }
37
+
38
+ }
Original file line number Diff line number Diff line change 2
2
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
3
3
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
4
4
| 463| [ Island Perimeter] ( https://leetcode.com/problems/island-perimeter/ ) | [ Solution] ( ../../blob/master/EASY/src/easy/IslandPerimeter.java ) | O(m* n)| O(1) | Easy|
5
+ | 462| [ Minimum Moves to Equal Array Elements II] ( https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ ) | [ Solution] ( ../../blob/master/MEDIUM/src/medium/MinimumMovestoEqualArrayElementsII.java ) | O(nlogn) | O(1) | Medium|
5
6
|459|[ Repeated Substring Pattern] ( https://leetcode.com/problems/repeated-substring-pattern/ ) |[ Solution] ( ../../blob/master/EASY/src/easy/RepeatedSubstringPattern.java ) | O(n)|O(n) | Easy| KMP
6
7
|456|[ 132 Pattern] ( https://leetcode.com/problems/132-pattern/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/_132Pattern.java ) | O(n) |O(n) | Medium| Stack
7
8
| 455| [ Assign Cookies] ( https://leetcode.com/problems/assign-cookies/ ) | [ Solution] ( ../../blob/master/EASY/src/easy/AssignCookies.java ) | O(n)| O(1) | Easy|
You can’t perform that action at this time.
0 commit comments