001 LeetCode problem solution: two numbers

Two numbers and

topic

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, 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

Example:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

Java:

Method One: Violence Act

Violence is simply to traverse the cycle twice manner nums

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

Complexity analysis:

  • Time complexity: O (n ^ 2)
    • For each element, we are trying to find the target element to which it corresponds to the rest of iterate, which will cost O (n) time. Thus the time complexity is O (n ^ 2)
  • Space complexity: O (1)

Method two: twice a hash table

In order to optimize run time complexity, we need a more efficient way to check whether the target element in the array. If there is, we need to find its index. What is the best way to keep each element of the array with its index of each other corresponds to? Hash table

By way trade space for speed, we can find the time reduced from O (n) to O (1). It is a hash table built for this purpose, it supports an approximately constant time to quickly find. I used the "approximate" to describe, because once the conflict could degenerate to O (n) time to find used. But as long as you carefully choose a hash function, to find in the hash table it should be amortized to O (1) time with

A simple implementation uses two iterations. In the first iteration, we add the value of each element and its index to the table. Then, in a second iteration, we will examine the target element (target - nums [i] target-nums [i]) corresponding to each element exists in the table. Note that this can not be the target element nums [i] nums [i] itself!

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

Complexity analysis:

  • Time complexity: O (n)
    • We have included a list of n elements traversed twice. Since the hash table lookup to shorten the time O (1), so the time complexity is O (n)
  • Space complexity: O (n)
    • The additional space required depends on the number of elements stored in the hash table, the table stores n elements

Method three: the hash table again

The fact that we can complete a. And performing iterative element inserted into the table at the same time, we will go back and check whether there is a target current element corresponding to the table. If it exists, then we have found a solution corresponding to, and immediately return it

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");
    }
}

Complexity analysis:

  • Time complexity: O (n)
    • We only have to traverse the list contains n elements once. Carried out in each table lookup takes only O (1) time
  • Space complexity: O (n)
    • The additional space required depends on the number of elements stored in the hash table, the table needs to store up to n elements

C++:

Method One: Violence Act

Violence is simply to traverse the cycle twice manner nums

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i,j;
        for(i=0;i<nums.size();++i){
            for(j=i+1;j<nums.size();++j){
                if(nums[i]+nums[j]==target){
                    return {i,j};
                }
            }
            
        }
        return {i,j};
    }
};

Complexity analysis:

  • Time complexity: O (n ^ 2)

    For each element, we are trying to find the target element to which it corresponds to the rest of iterate, which will cost O (n) time. Thus the time complexity is O (n ^ 2)

  • Space complexity: O (1)

Method two: twice hashing

The method to achieve with map, map is an associative container STL, which provides one to one (the first of which can be called keywords, each can appear only once in the map, the second might be called the key the value of the word) data processing capability

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> a;//建立hash表存放数组元素
        vector<int> b(2,-1);//存放结果
        for(int i=0;i<nums.size();i++){
            a.insert(map<int,int>::value_type(nums[i],i));
        }
        for(int i=0;i<nums.size();i++){
            if(a.count(target-nums[i])>0&&(a[target-nums[i]]!=i)){
            //判断是否找到目标元素且目标元素不能是本身
                b[0]=i;
                b[1]=a[target-nums[i]];
                break;
            }
        }
        return b;
    };
};

Complexity analysis:

  • Time complexity: O (n)
    • We have included a list of n elements traversed twice. Since the hash table lookup to shorten the time O (1), so the time complexity is O (n)
  • Space complexity: O (n)
    • The additional space required depends on the number of elements stored in the hash table, the table stores n elements

Method three: again hashing

Improvements in the hash method twice: during the iterative and elements inserted into the table at the same time, we will go back and check whether there is a target current element corresponding to the table. If it exists, then we have found a solution corresponding to, and immediately return it

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> a;//提供一对一的hash
        vector<int> b(2,-1);//用来承载结果,初始化一个大小为2,值为-1的容器b
        for(int i=0;i<nums.size();i++){
            if(a.count(target-nums[i])>0){
                b[0]=a[target-nums[i]];
                b[1]=i;
                break;
            }
            a[nums[i]]=i;//反过来放入map中,用来获取结果下标
        }
        return b;
    };
};
  • Time complexity: O (n)
    • We only have to traverse the list contains n elements once. Carried out in each table lookup takes only O (1) time
  • Space complexity: O (n)
    • The additional space required depends on the number of elements stored in the hash table, the table needs to store up to n elements

Python:

Method One: Violence Act

Solving with Python-related function list of
problem-solving major key is to find num2 = target - num1, whether the list also, then you need to use the following two methods:

num2 in nums, True Instructions being returned Me
nums.index (num2), look for the index num2

def twoSum(nums, target):
    lens = len(nums)
    j=-1
    for i in range(lens):
        if (target - nums[i]) in nums:
            if (nums.count(target - nums[i]) == 1)&(target - nums[i] == nums[i]):#如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
                continue
            else:
                j = nums.index(target - nums[i],i+1)#index(x,i+1)是从num1后的序列后找num2                
                break
    if j>0:
        return [i,j]
    else:
        return []

Method Two:

Performed by, but takes a long time, a total of 1636ms.

In a method based on the optimal solution. Thinking, num2 do not need to look to find each from nums again, you can just look num1 position from before or after. But in order to facilitate the index here select Find from the previous position num1

def twoSum(nums, target):
    lens = len(nums)
    j=-1
    for i in range(1,lens):
        temp = nums[:i]
        if (target - nums[i]) in temp:
            j = temp.index(target - nums[i])
            break
    if j>=0:
        return [j,i]

Executed by shortening the time-consuming more than half, a total of 652ms.

Method three: Analog hash dictionary

This approach compared to the method is actually a dictionary record the value and location of num1 and num2, while saving the steps and then find num2 index

def twoSum(nums, target):
    hashmap={}
    for ind,num in enumerate(nums):
        hashmap[num] = ind
    for i,num in enumerate(nums):
        j = hashmap.get(target - num)
        if j is not None and i!=j:
            return [i,j]

Through a dictionary and look for efficiency much faster, significantly reduce execution speed, a total of 88ms.

Method four:

Similar to the second method does not require mun2 do not need to go to find throughout the dict. Dict can be found in the previous num1, so you only need to solve the cycle

def twoSum(nums, target):
    hashmap={}
    for i,num in enumerate(nums):
        if hashmap.get(target - num) is not None:
            return [i,hashmap.get(target - num)]
         hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况

hashmap [num] = i # phrase can not be placed before the if statement to address list in duplicate values or target-num = num case
, but compared to the method of method four three speed imaging method not two compared to the method of a speed boost. In the multi-speed 70ms

Guess you like

Origin www.cnblogs.com/MessiXiaoMo3334/p/11518008.html