【leetCode】001Two Sum

来源:互联网 发布:部落地震法术数据 编辑:程序博客网 时间:2024/06/02 10:57

【链接】: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].
Subscribe to see which companies asked this question.
【思路】:
C代码:

int main(){    int n,arr[maxn];    int target;    int ri,rj;    memset(arr,0,sizeof(arr));    scanf("%d",&n);    for(int i=0; i<n; ++i)        scanf("%d",&arr[i]);    scanf("%d",&target);     for(int i=0; i<n; ++i){            for(int j=i+1; j<n; ++j){                  if(arr[j]==(target-arr[i]))                  ri=i;                  rj=j;                  break;            }            break;     }     printf("%d %d\n",ri,rj);     return 0;}

C++代码:

class Solution{public:    vector <int> twoSum(vector<int>&nums,int target)    {        unordered_map<int,int> map;        for(int i=0; i<nums.size(); ++i){            auto tp=map.find(target-nums[i]);            if(tp!=map.end())            {                return {tp->second,i};            }            map[nums[i]]=i;        }    }};

 unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序,

存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。

1 0
原创粉丝点击