[Double pointer] 1679. The maximum number of K and number pairs

[Double pointer] 1679. The maximum number of K and number pairs

problem solving ideas

  • use double pointer
  • Sort the array first from small to large
  • Then set the front and back pointers
  • Compare the sum of the numbers of the front and back pointers and compare whether it is the same as k and then move the pointer
class Solution {
    
    
    public int maxOperations(int[] nums, int k) {
    
    
        // 最暴力的方法 两层for循环

        // 双指针  
        // 先对数组进行排序 然后设置首尾指针 比较前后指针的数字之和 计算是不是k
        int i = 0;
        int j = nums.length - 1;

        Arrays.sort(nums);// 数组从小到大进行排序
        int count = 0;

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

        return count;

    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/131753818