[LeetCode][JAVA] 1679. Max Number of K-Sum Pairs

탱귤생귤·2023년 12월 23일
0

LeetCode

목록 보기
12/16


I used brute-force again……..that’s because I forgot that I could do Arrays.sort …I should study java more. I forgot too many of java.

private static int maxOperations(int[] nums, int k) {
        int cnt = 0;

        int n = nums.length;

        for (int i = 0; i <= n - 2; i++) {
            if (k > nums[i] && nums[i] != 0) {
                for (int j = i + 1; j <= n - 1; j++) {
                    if (nums[i] + nums[j] == k && nums[j] != 0) {
                        nums[i] = 0;
                        nums[j] = 0;
                        cnt++;
                        break;
                    }
                }
            }
        }

        return cnt;
    }

Second code is new code using Arrays.sort.

private static int maxOperations(int[] nums, int k) {
        int cnt = 0;
        Arrays.sort(nums);

        int i = 0;
        int j = nums.length - 1;

        while (i < j) {
            if (k <= nums[i]) break;
            while (j > i) {
                int sum = nums[i] + nums[j];
                if (sum == k) {
                    cnt++;
                    break;
                } else if (sum > k) j--;
                else i++;
            }
            i++;
            j--;

        }

        return cnt;
    }

Last one is using HashMap. I saw this code at the discussion tab.

private static int maxOperations(int[] nums, int k) {
        Map<Integer, Integer> map = new java.util.HashMap<>();
        int cnt = 0;
        for (int i = 0; i < nums.length; i++) {
            int res = k - nums[i];
            if (map.containsKey(res)) {
                cnt++;
                if (map.get(res) == 1) map.remove(res);
                else map.put(res, map.get(res) - 1);
            } else {
                /*map.getOrDefault(map.get(nums[i]),0)+1
                this is because if nums[i] is in the map, get that value or put the value as 0 and add 1 to both of them.
                 */
                map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            }
        }

        return cnt;
    }

0개의 댓글