Leetcode01 两数之和

问题描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

//暴力求解(cpp)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int num;
        vector<int> a;
        for(int i = 0; i < nums.size(); ++i){
            num = target - nums[i];
            for(int j = i + 1; j < nums.size(); ++j){
                if(num == nums[j]){
                    a.push_back(i);
                    a.push_back(j);
                    return a;
                }
            }
        }
        return a;
    }
};
//哈希法(cpp)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> a;
        vector<int> b(2,-1);
        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;  
        }
        return b;
    }    
};
#hash(python)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict = {}
        for i,m in enumerate(nums):
            if dict.get(target - m) is not None:
                return [dict.get(target - m), i]
            dict[m] = i
        return []
        '''
        #暴力求解
        array = []
        for i in range(len(nums)):
            num = target - nums[i]
            for j in nums[i+1:]:
                if j == num:
                    return [i,nums[i+1:].index(j)+i+1]
        return []
        '''

你可能感兴趣的:(LeetCode数组部分,Leetcode)