1 Sum of two numbers (map, fast and slow pointer)

1. Problem description:

Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array, and return their array index.

You can assume that each input will only correspond to one answer. However, you cannot reuse the same elements in this array.

Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums [0] + nums [1] = 2 + 7 = 9,
it returns [0, 1]

Source: LeetCode
link: https://leetcode-cn.com/problems/two-sum

2. Thinking analysis:

① The problem is not difficult to understand. At the beginning, I thought of using recursion to solve. In the recursive method, two pointers are used: one is the left pointer and the other is the right pointer. We can have two possible operations when calculating , One is that the left pointer moves one bit, the right pointer does not move, and the other is that the left pointer does not move, and the right pointer moves one bit to the left, so it corresponds to two parallel states, so two methods are used. Just recurse, and use a two-dimensional array to record the results of the solution during recursion. When recursively find that the solution has been solved before, then return directly, but the memory limit is exceeded when submitting, it may be data The amount is too large, so another method is used to solve

② Due to the use of recursive timeout, map is used for mapping. At the beginning, the entire array is traversed, and the corresponding values ​​in the array are mapped to the following table corresponding to the value, and the value of the Deque type can avoid two problems. The elements of the array are the same. The use of map to map array values ​​and subscripts is mainly to find the subscript values ​​corresponding to the numbers before sorting after sorting. We use map to map and sort the array in the loop. Use the left and right pointers to operate, if the left pointer is too small, the right pointer is moved to the left until the two elements are equal, so that the problem of recursive timeout can be avoided

③ In the official solution, it combines the situation where at most two numbers appear in the problem, so use a for loop traversal combined with a hash table to solve, and use the subtraction situation to find another number when solving The mapping situation, from solving the problem of the mapping of repeated numbers and the efficiency of the query, the code written is very good

3. The code is as follows:

Code I wrote myself:

class Solution {
     public int[] twoSum(int[] nums, int target) {
        int res[] = new int[2];
        Map<Integer, Deque<Integer>> map = new HashMap<>();
        /*使用map来进行记录*/
        for (int i = 0; i < nums.length; ++i){
            map.put(nums[i], map.getOrDefault(nums[i], new ArrayDeque()));
            map.get(nums[i]).add(i);
        }
        Arrays.sort(nums);
        /*使用快慢指针来解决*/
        int l = 0, r = nums.length - 1;
        while (l < r){
            if (nums[l] + nums[r] == target){
                res[0] = map.get(nums[l]).pop();
                res[1] = map.get(nums[r]).pop();
                return res;
            }else if (nums[l] + nums[r] < target) ++l;
             else --r;
        }
        return null;
    }
}
class Solution {
    int res[] = new int[2];
    int rec[][];
    public int[] twoSum(int[] nums, int target) {
        rec = new int[nums.length][nums.length];
        recursion(nums, target, 0, nums.length - 1);
        return res;
    }

    /*使用一个数组来记录中间的求解过程*/
    private void recursion(int[] nums, int target, int l, int r) {
        if (l >= r) return;
        if (rec[l][r] == -1) return;
        if (nums[l] + nums[r] == target){
            res[0] = l;
            res[1] = r;
            return;
        }
        /*存在两个平行的状态: l加r不变, l不变r减*/
        recursion(nums, target, l + 1, r);
        recursion(nums, target, l, r - 1);
        rec[l][r] = -1;
    }
}

Official code:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

 

Published 569 original articles · Like 153 · Visits 590,000+

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/105423280