1.题目:
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].
2.思路:
遍历整个数组,对于便利到的每个数组元素,向后寻找,是否存在某个元素等于target于此元素的差。找到则返回。
3.注意:
4.代码 sample one : C
//结果数组需要动态分配
int* twoSum(int* nums, int numsSize, int target) {
int rest = 0 ,i = 0, j = 0;
int * result = (int *)malloc(sizeof(int) * 2);
for(i ; i<numsSize ; i++){
rest = target - nums[i];
for(j=i+1 ; j<numsSize ; j++){
if (nums[j] == rest){
printf("[%d,%d]",i,j); // for test
result[0]=i,result[1]=j;
return result;
}
}
}
return result;
}
sample two: C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result ;
int size = nums.size();
for(int i = 0; i < size; i++){
int rest = target - nums[i];
for(int j = i+1 ;j < size;j++){
if( nums[j] == rest ){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
}
};
sample three: python
class Solution(object):
def twoSum(self, nums, target):
for i in range(0,len(nums)):
rest = target - nums[i]
for j in range(i+1,len(nums)):
if nums[j] == rest:
list = [i,j]
return list
sample:java
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i = 0;i < nums.length;i++){
int rest = target - nums[i];
for(int j = i+1; j < nums.length ; j++){
if( nums[j] == rest){
result[0]=i;
result[1] =j;
return result;
}
}
}
return result;
}
}
熟悉一下各门语言,没用什么技巧,就是简单的数组遍历。复习知识点:java容器,python面向对象编程
看了一下这几门语言点赞数最高的答案,都使用了hash表来提高效率。明天复习一下hash吧!
看了一下这几门语言点赞数最高的答案,都使用了hash表来提高效率。明天复习一下hash吧!