LeetCode 1. Two Sum

Posted 来一点音乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 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].

思路: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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 1 Two Sum

[LeetCode] 1 Two Sum

LeetCode之371. Sum of Two Integers

leetcode 1.Two sum

Leetcode 1. Two Sum (Python)

LeetCode #1 - Two Sum