Double pointer solves the problem of the sum of two numbers

Everyone knows a lot of things, but smart people don't say it


Regarding the problem of the sum of two numbers , the array nums and the target value target are generally given . To deal with this kind of problem, the following two points should be paid attention to:

  1. whether the array is ordered;

  2. Given the target value target, discuss according to the sum of the two numbers and the size of the target:
    - equal to target
    - less than target
    - greater than target

  3. The return value is the subscript or the number of schemes

    If the return value is required to be a subscript , we cannot solve it by sorting and double-pointer solutions when the array is unordered .

Combined with the topic of Leetcode , we discuss the situations listed above one by one.

The first category: equal to target

1. The sum of two numbers

Given an integer array nums and an integer target value target , please find , and return their array subscripts .

According to the above summary, we can find out the key points:

  1. array unordered;
  2. The sum of the two numbers is equal to the target;
  3. return array subscript;

So this question excludes the solution of sorting + double pointer . It is recommended to use a hash table to reduce the time complexity to a constant level.

The idea of ​​solving the problem is to traverse the array, and for each element num, query whether there is a corresponding target - num.

	public int[] twoSum(int[] nums, int target) {
    
    
        int[] result = new int[2];

        if(nums == null || nums.length == 0){
    
    
            return result;
        }
        // 注意key为nums[i],value为下标
        HashMap<Integer,Integer> hashMap = new HashMap<>();

        for(int i = 0;i < nums.length; i++){
    
    

            if(hashMap.containsKey(target-nums[i])){
    
    
                result[0] = i;
                result[1] = hashMap.get(target-nums[i]);
                return result;
            }

            hashMap.put(nums[i],i);
        }
        return result;
    }

PS: It can also be implemented by storing target-nums[i] in a hash table. The principle is the same.

1.2 Frequently Asked Questions

Many students have doubts about who is the key and who is the value in the hash table here ? Believe in yourself, you are not alone in this confusion .

Solemnly declare here:

  • key ——— element num[i] or target-nums[i]
  • value ——— element subscript

A lot of confusion is due to the fact that when there are duplicate elements in the array , it will be overwritten as a key.
For this question, it is clear in the title that there will only be one valid answer . In this case, even if there are repeated elements, find a set of solutions and return directly.

So the question is, assuming that there may be multiple sets of solutions, is this solution still valid?

Answer: yes

for example:

The input use case is [1,1,2,5], target = 3

When traversing to the second 1, hashMap will overwrite the previous 1, and then continue to execute. Finally, the set of valid answers [2,1] will be returned.

color
What is done on paper will eventually become shallow, and I will never know that this matter must be practiced

When solving algorithm problems, many times it is not that we have no ideas, but that we have not really started to realize it.


167. Sum of Two Numbers II - Input Sorted Array

You are given an integer array numbers whose subscript starts from 1. The array has been arranged in non-decreasing order. Please find two numbers from the array that satisfy the sum of the sum to be equal to the target number target. If these two numbers are numbers[index1] and numbers[index2] respectively, then 1 <= index1 < index2 <= numbers.length.
Returns the indices index1 and index2 of these two integers as an array of integers of length 2 [index1, index2].

key point:

  1. The array is ordered - arranged in non-decreasing order;
  2. Find two numbers whose sum is equal to the target number target;
  3. Return subscript and index1 < index2;
  4. Subscripts start from 1;

In the case of an ordered array, double pointers , which one is better than me?

as the picture shows

 public int[] twoSum(int[] numbers, int target) {
    
    
        int[] result = new int[2];
        if(numbers == null || numbers.length == 0){
    
    
            return result;
        }

        int left = 0;
        int right = numbers.length - 1;

        while(left < right){
    
    
           int sum =  numbers[left]+numbers[right];
            if( sum == target){
    
    
            	// 因为下标从1开始,
                result[0] = left+1;
                result[1] = right+1;
                return result;
            }

            if(sum < target){
    
    
                left++;
            }else{
    
    
                right--;
            }
        }

        return result;
    }

Let’s make up for it by the way— the sword refers to Offer 57. The sum is the two numbers of s


The second category: less than target

1099. The Largest Sum of Two Numbers Less Than K

Given an integer array nums and an integer k, return the largest sum sum such that there exists i < j such that nums[i] + nums[j] = sum and sum < k. Returns -1 if no i,j satisfying this equation exists.

key point:

  1. array unordered
  2. (sum = nums[i] + nums[j]) < k;
  3. Return the largest and sum as large as possible;

Don't think about it, sorting + double pointers .

 public int twoSumLessThanK(int[] nums, int k) {
    
    
        if(nums == null || nums.length == 0){
    
    
            return -1;
        }

        Arrays.sort(nums);

        int left = 0;
        int right = nums.length-1;

        int result = -1;

        while(left < right){
    
    
            int sum = nums[left] + nums[right];
            if(sum >= k){
    
    
                right--;
            }else{
    
    
            	// 求最大和
                result = Math.max(result,sum);
                left++;
            }
        }

        return result;
    }

LCP 28. Procurement Program

Xiaoli stores the quotations of N parts in the array nums. Xiaoli's budget is target, assuming that Xiaoli only purchases two parts, and the cost of purchasing parts is required not to exceed the budget, how many procurement plans does he have?

Note: The answer needs to be modulo 1e9 + 7 (1000000007), for example: the initial calculation result is: 1000000008, please return 1

Summarize the key points:

  1. array unordered;
  2. num[i] + num[j] <= target;
  3. Find the number of schemes that meet the conditions ;

This question is a competition question. Let's take a look at the common questions of the students:
insert image description here
I have nothing to say about it, but Zhang Fei gave it to everyone three times.
insert image description here

There is a core element to solve this problem: the locking of the number of solutions (right boundary - left boundary) .
insert image description here

public int purchasePlans(int[] nums, int target) {
    
    
        if(nums == null || nums.length == 0){
    
    
            return 0;
        }
		// 排序
        Arrays.sort(nums);

        int result = 0;

        int left = 0;
        int right = nums.length - 1;

        while(left <= right){
    
    
            int sum = nums[left] + nums[right];
            if(sum > target){
    
    
                right --;
            }else{
    
    
            	// 这里利用[left,right]的元素都符合sum <= target的特性,直接得出方案数为right - left.
                result += (right - left);
                result %= (1000000007);
                left++;
            }
        }
        return result;
    }

Guess you like

Origin blog.csdn.net/wangcheeng/article/details/124535079