美文网首页
LeetCode 1. Two Sum

LeetCode 1. Two Sum

作者: 洛丽塔的云裳 | 来源:发表于2020-03-27 00:12 被阅读0次

0. 题目

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].

1. C++版本

错误版本。对数组直接进行排序,这样就不能获取原来的下标!!!

vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> res;
    sort(nums.begin(), nums.end());
    for (int i=0, j=nums.size()-1; i<j; ) {
        if (target < nums[i] + nums[j]) {
            j--;
        }
        else if (target > nums[i] + nums[j]) {
            i++;
        }
        else {
            res.push_back(i);
            res.push_back(j);
            return res;
        }
    }
    return res;
}

提交通过版本:算法复杂度O(N2),比较高, 耗时596 ms

    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        for (int i=0; i<nums.size()-1; i++){
            for (int j=i+1; j<nums.size(); j++){
                if (target == nums[i] + nums[j]) {
                    res.push_back(i);
                    res.push_back(j);
                    return res;
                }
            }
        }
        return res;
    }
};

2. python版本

提交通过版本:算法复杂度O(N2),比较高, 耗时4524 ms

 def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    res = []
    length = len(nums)
    for i in range(0, length):
        for j in range(i+1, length):
            if target == nums[i] + nums[j]:
                res.append(i)
                res.append(j)
            return res
    return res

相关文章

网友评论

      本文标题:LeetCode 1. Two Sum

      本文链接:https://www.haomeiwen.com/subject/bmahuhtx.html