【LeetCode】Two Sum (C++)

最近花了点时间了解了下C++,感觉与C还是有很多不同的。接下来坚持每天用C++写五道LeetCode。fighting!

题目:

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


代码:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n=nums.size();
        vector<int> ans;
        map<int,int> m;
        for(int i=0; i<n; i++)
            m[nums[i]]=i;
        for(int i=0; i<n; i++){
            int t=target-nums[i];
            if(m.count(t)&&m[t]!=i){
                ans.push_back(i);
                ans.push_back(m[t]);
                break;
            }
        }
        return ans;
    }
};

这个代码10ms通过了。

下面这个是之前写的C,就是两重循环,比较基础,运行了76ms。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int i,j;
    int* a=(int*)malloc(2*sizeof(int));
    for(i=0;i<numsSize;i++)
    {
        for(j=i+1;j<numsSize;j++)
        {
            if(nums[i]+nums[j]==target)
            {
                a[0]=i;
                a[1]=j;
            }
        }
    }
    return a;
}


猜你喜欢

转载自blog.csdn.net/biongbiongdou/article/details/80207243