码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 1. Two Sum

时间:2018-02-19 13:30:27      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:目标   ssi   str   hashmap   gpo   shm   size   targe   ++   

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.枚举判断每个元素与另一个元素之和是否等于目标值
   2.哈希查找,将所有元素存入hashmap中,目标值减去每个元素等于某个值。看这个值是否等于剩下某个元素。
 1 int* twoSum(int* nums, int numsSize, int target) {
 2     int *a = (int *)malloc(2*sizeof(int));
 3     int num = 0;
 4     for(int i=0;i<numsSize;i++){
 5         for(int j=i+1;j<numsSize;j++){
 6             if(nums[i]+nums[j]==target){
 7                 a[0] = i;
 8                 a[1] = j;
 9             }
10         }
11     }
12     return a;
13     
14 }

 

LeetCode 1. Two Sum

标签:目标   ssi   str   hashmap   gpo   shm   size   targe   ++   

原文地址:https://www.cnblogs.com/lolybj/p/8453707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!