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

大致意思:输入一个数组和一个目标数,如果能在这个数组中找到两个元素的和等于目标数,那么就输出这两个数的下标,每次输入用例时,都保证只有一个结果,每个元素使用一次。

常规解法:两层循环嵌套,依次遍历,每两个元素都做一次相加运算看是否等于目标数,直到找到这样两个数,返回下标。时间复杂度太高。

/**
Note: The returned array must be malloced, assume caller calls free().
*/

int* twoSum(int* nums, int numsSize, int target) {
  int arr=(int *)malloc(sizeof(int)3);
  for(int i=0;i<numsSize;++i)
  {
    for(int j=i+1;j<numsSize;++j)
    {
        if(i!=j && nums[i]+nums[j]==target)
        {
            arr[0]=i;
            arr[1]=j;
            break;
        }
    }
  }
  return arr;
}

其他解法:
用哈希表,对数组进行一次遍历,每遍历数组中的一个元素,就用目标数减去该元素,看得到的结果是否存在哈希表中,如果不存在将该元素放入哈希表,继续遍历,直到找到结果在哈希表中,则找到这两个元素,返回对应下标。时间复杂度相对较低。

class Solution {
public:
  vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> index;
    unordered_map<int, int> hash;
    for(int i=0; i<nums.size(); ++i) {
        auto it = hash.find(target-nums[i]);
        if(it != hash.end()) {
            index.push_back(min(i, it->second)+1);
            index.push_back(max(i, it->second)+1);
            return index;
        }
        else hash[nums[i]] = i;
    }
  }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容