Open songyy5517 opened 6 months ago
Approach: Sort & Two Pointers
k
:
(1)If they are equal, then move both pointers to the next position, and update the global variable;
(2)If sum > k
, move the right pointer; otherwise, move the left pointer.Complexity Analysis
class Solution {
public int maxOperations(int[] nums, int k) {
// Intuition: Two pointers (Collision).
// 1. Exception handling
if (nums == null || nums.length == 0)
return 0;
// 2. Define two pointers and a global variable
int left = 0, right = nums.length - 1;
int num = 0;
// 3. Sort the array.
Arrays.sort(nums);
// 4. Loop through the array
while (left < right){
if (nums[left] + nums[right] == k){
num ++;
left ++;
right --;
}
else if (nums[left] + nums[right] > k)
right --;
else
left ++;
}
return num;
}
}
2024/5/11
You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array.
Example 1:
Example 2:
Intuition The problem is to find all pairs in the array that sum up to k. Consider finding pairs, a straightforward idea is to first sort the array in ascending order. Then we use to two collision pointers starting from the left and right side respectively. While moving two pointer towards each other, we compare the sum of the two pointers with
k
, record the number of valid pairs, and update pointers correspondingly.