Advertisement
1988coder

561. Array Partition I

Apr 16th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/array-partition-i/
  3.  
  4. import java.util.Arrays;
  5.  
  6. /**
  7.  * Refer:
  8.  * https://leetcode.com/problems/array-partition-i/discuss/102170/Java-Solution-Sorting.-And-rough-proof-of-algorithm.
  9.  *
  10.  * Time Complexity: O(N log N + N). Sorting + Iterating over sorted array.
  11.  *
  12.  * Space Complexity: O(N). Space required for sorting.
  13.  *
  14.  * N = Length of input array.
  15.  */
  16. class Solution1 {
  17.     public int arrayPairSum(int[] nums) {
  18.         if (nums == null || nums.length % 2 != 0) {
  19.             return 0;
  20.         }
  21.  
  22.         Arrays.sort(nums);
  23.         int pairSum = 0;
  24.  
  25.         for (int i = 0; i < nums.length; i += 2) {
  26.             pairSum += nums[i];
  27.         }
  28.  
  29.         return pairSum;
  30.     }
  31. }
  32.  
  33. /**
  34.  * Refer:
  35.  * https://leetcode.com/problems/array-partition-i/discuss/102180/Java-O(n)-beats-100
  36.  *
  37.  * Time Complexity: O(N + 20001).
  38.  *
  39.  * Space Complexity: O(20001).
  40.  *
  41.  * N = Length of input array.
  42.  */
  43. class Solution2 {
  44.     public int arrayPairSum(int[] nums) {
  45.         if (nums == null || nums.length % 2 != 0) {
  46.             return 0;
  47.         }
  48.  
  49.         int[] count = new int[20001];
  50.         int max = Integer.MIN_VALUE;
  51.         int min = Integer.MAX_VALUE;
  52.         for (int n : nums) {
  53.             int idx = n + 10000;
  54.             count[idx]++;
  55.             max = Math.max(max, idx);
  56.             min = Math.min(min, idx);
  57.         }
  58.  
  59.         int pairSum = 0;
  60.  
  61.         boolean even = true;
  62.         for (int i = min; i <= max; i++) {
  63.             while (count[i] > 0) {
  64.                 if (even) {
  65.                     pairSum += i - 10000;
  66.                 }
  67.                 even = !even;
  68.                 count[i]--;
  69.             }
  70.         }
  71.  
  72.         return pairSum;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement