- 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思想:(1)暴力解法,直接从数组开始访问到数组结束。由于python的语法不是特别熟悉,不知道有哪些可用的包或者函数,所以写的很是生涩,当然效率也很低。
// 时间复杂度O(n^2)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
twoSum = []
for i in range(0, len(nums)):
a = target - nums[i]
for j in range(i+1, len(nums)):
if(a == nums[j]):
twoSum.append(i)
twoSum.append(j)
return twoSum
//同样的思想用C
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int *twoSum = (int *)malloc(sizeof(int)*2);
int temp;
for(int i=0;i<numsSize;i++){
temp = target - nums[i];
for(int j=i+1;j<numsSize;j++){
if(temp == nums[j]){
twoSum[0]=i;
twoSum[1]=j;
return twoSum;
}
}
}
return 0;
}
- 这个题目提升一下,变成是三个数之和。题目描述如下:给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
注意事项:在三元组(a, b, c),要求a <= b <= c。结果不能包含重复的三元组。
样例
如S = {-1 0 1 2 -1 -4}, target = 0
你需要返回的三元组集合的是:(-1, 0, 1), (-1, -1, 2)
思路:(1) 首先,将数组按从小到大的排序,然后从头挑选一个元素,接着使用首尾两个指针来挑选后两个元素。[略]