1. 程式人生 > >LeetCode 1. Two Sum

LeetCode 1. Two Sum

所有 specific assume alloc hat put integer have each

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