The classic problem using a lookup table

Example 1: two numbers

Given an integer array nums and a target value target, you find in the array and the target value of the two integers, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Use the Find Set approach is, to all the elements and the corresponding index are placed in the map, then look each target-aexists in the map, in the words of the return aand target-athe index value.
However, if there are two identical elements of how to do? To do this, they put in the time map of the sentence off, if not found at this point look-up table target-a, put ainto the map; If found return it.

1. sum Noriyuki three number

Give you an array of integers containing the nums n, determines whether there are three elements a, b, c nums so that the + B + C = A 0
? Please do not satisfy the conditions you find all duplicate triples.

Note: The answer can not contain duplicate triples.

I thought for a long time, we are unable to see how lookup set to resolve. With examples just looks like nothing, but very different approach.
Different approaches, but one thing is the same, that is, for a, b and find the c, so that b + c == target-a.
However, the problem most difficult thing is how to weight. After all, it is not required by the order, then there will be the use of different elements, but the resulting triples is the same .
So, take the following way:

  1. Sorting an array
  2. Traversing from left to right, for each element nums [i], using the double pointer to traverse to find ithe element after , L the left end point, R pointing right.
  3. If nums [i]> 0, and the sum of the three can not necessarily equal to 0, the loop ends
  4. If nums [i] == nums [i -1], it indicates that the number is repeated and results are repeated , we should skip
  5. When the sum == 0 when, the nums [L] == the nums [L +. 1] can lead to duplicate a result, should skip, L ++
  6. When == 0 SUM, the nums [R & lt] == the nums [-R & lt. 1] can lead to duplicate a result, you should skip, R-

Why can this happen? In fact, if the law is violence, then when each of the next layer cycle will continue to back down from the current standard , and meet the current layer repeating elements will be skipped, then it will avoid duplication. Here just three cycles of two layers by a double pointer simplified, but the de-emphasis method is the same.
Time complexity: O (n- 2 )

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;i++){
            if(nums[i]>0) break;
            if(i>0 && nums[i]==nums[i-1]) {
                continue;
            }
            int l = i+1;
            int r = nums.length-1;
            while(l<r){
                int sum = nums[i]+nums[l]+nums[r];
                if(sum==0){
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    while(l<r && nums[l]==nums[l+1]) l++;
                    while(l<r && nums[r]==nums[r-1]) r--;
                    res.add(list);
                    l++;
                    r--;
                }
                else if(sum>0)  r--;
                else l++;
            }
        }
        return res;
    }
}

2. four and the number of

Given a n array of integers and a target nums target, if there are four elements a, b, c, and d is determined nums so that + A
B + C + d is equal to the value of the target? Identify all satisfy the conditions of the quad and do not repeat.

note:

The answer can not contain duplicate quad.

Compared to three digital sum, it is not only needed in the first layer and the circulation of the collision between a pointer add a layer to it?
It proved to be feasible, but this time became the complexity O (the n- 3 ).

class Solution {
    public List<List<Integer>> fourSum(int[] nums,int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-3;i++){   //a
            if(i>0 && nums[i]==nums[i-1]) {
                continue;
            }
            for(int j=i+1;j<nums.length-2;j++){   //b
                if(j>i+1 && nums[j]==nums[j-1]) continue;
                int l = j+1;
                int r = nums.length-1;
                while(l<r){
                    int sum = nums[i]+nums[j]+nums[l]+nums[r];
                    // System.out.println(nums[i]+" "+nums[j]+" "+nums[l]+" "+nums[r]);
                    if(sum==target){
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[l]);
                        list.add(nums[r]);
                        while(l<r && nums[l]==nums[l+1]) l++;
                        while(l<r && nums[r]==nums[r-1]) r--;
                        res.add(list);
                        l++;
                        r--;
                    }
                    else if(sum>target)  r--;
                    else l++;
                }
            }
            
        }
        return res;
    }
}

Third, the number of the nearest three and

Given an array comprising n integers and a target nums target. Nums identify the three integers, and a target such that their
closest. The three numbers and return. Each group assumes that there is only input the only answer.

For example, given the array nums = [-1,2,1, -4], and target = 1.

The closest target is three and the number 2. (-1 = 1 + 2 + 2).

And triple the number of ideas is the same and the same, the difference is that here is no longer a comparison for equality, but more sum-targetwho the absolute value is smaller. The smaller the update results, prior to the optimization of ideas and the same.

Example 2: four numbers together II

Given an array of integers containing the list of four A, B, C, D, there is calculated the number of tuples (i, j, k, l ), such that A [i] + B [j ] + C [k] + D [l] = 0.

In order to simplify the problem, all of the A, B, C, D have the same length N, and 0 ≤ N ≤ 500. All integers in the range of -228 to 228-- between 1, the final result will not exceed 231--1.

This is very simple, with only two double loop, dual loop through all the first A, value B, and then adding the sum and a corresponding number of occurrences is recorded in a map.
Why should record the number of times? Because the subject did not say allowed to repeat Moreover, the added value of two different combinations may also be the same.
The second double loop to iterate through all of the C + D, and then see -C-Dif you can exist in the map, plus there is the number of occurrences in total.

First, the letter ectopic grouping words

Given a string array, ectopic word letters together. Ectopic word letters refer to the same letters, but arranged in different strings.
Example:
Input: [ "eat", "tea ", "tan", "ate", "nat", "bat"],
Output:
[
[ "ATE", "EAT", "TEA"],
[ "NAT "," Tan "],
[" BAT "]
]

The idea is to use a lookup table map, which is characterized in letters ectopic words, according to the alphabetical order is the same string. Therefore, according to the consistency of the string sorted as Key , to each of the corresponding letter of the word into ectopic List as a value .
Which uses java here before several unfamiliar methods:

  1. String str = String.valueOf(strArr);You can char [] into String.
  2. new ArrayList<>(map.values());Value map can be converted to a List.

Code is as follows: The time complexity of O (n)

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for(int i=0;i<strs.length;i++){
            char[] strArr = strs[i].toCharArray();
            Arrays.sort(strArr);
            String str = String.valueOf(strArr);
            if(map.containsKey(str)){
                map.get(str).add(strs[i]);
            }else{
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                map.put(str,list);
            }
        }
        return new ArrayList<>(map.values());
    }
}

Number of Boomerang: 3 examples

A tuple (i, j, k) set on a plane different points n "boomerang" is represented by a point, wherein the distance between the distance between the i and j and i and k are equal (taking into account membered order for the group).

Find the number of all boomerang. You can assume up to 500 n, the coordinates of all points in the closed interval [-10000, 10000] in.

Thinking through each point p, p to find all the distances of the other points, then the distance as the key, in order to p distance of key points as the value. Each time find a new point, can the same distance, and all other points of the constitution two boomerang .
Double loop needs, complexity is O (n- 2 ).

class Solution {
    public int numberOfBoomerangs(int[][] points) {
        int ans = 0;
        for(int q=0;q<points.length;q++){
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int w=0;w<points.length;w++){
                if(q!=w){
                    int dis = (points[q][0]-points[w][0])*(points[q][0]-points[w][0])+(points[q][1]-points[w][1])*(points[q][1]-points[w][1]);
                    if(map.containsKey(dis)){
                        int n = map.get(dis);
                        ans += 2*n;
                        map.replace(dis,n+1);
                    }else{
                        map.put(dis,1);
                    }
                }
            }
        }
        return ans;
    }
}
Published 60 original articles · won praise 6 · views 1203

Guess you like

Origin blog.csdn.net/DLC990319/article/details/105055711