leetcode [1] - Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Title effect : Given an array of numbers and a target, target output array index is the sum of the two numbers.

Understood : Method a: Violence, directly through the array, the i-th access, determines target - nums [i] in the presence or absence of the array. The time complexity is O (n ^ 2), the spatial complexity is O (1).

    Method two: hashing, hash lookup time is almost linear, when traversing the array, the i-th access, determines target - nums [i] whether a hash table exists, the current value or the nums [i] and index [i] exists hash table.

++ Code C :

One - Violence Act:

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

Method two - the hash table method:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> vec;
        unordered_map<int,int> map;
        int n = nums.size();
        for(int i=0;i<n;++i){
            unordered_map<int,int>::iterator it;
            it = map.find(target-nums[i]);
            if(it!=map.end()){
                vec.push_back(i);
                vec.push_back(it->second);
                break;
            }
            map.insert(make_pair(nums[i],i));
        }
        return vec;
    }
};

 

Guess you like

Origin www.cnblogs.com/lpomeloz/p/10938019.html