python实现
方法一(自己实现,80ms):
思路:先记录每个数的索引,然后排序n(nlog(n)),最后两个指针往中间走,即两个数值过大右指针向左移,反之向后移,时间复杂度为(n)。一共n(log(n))的时间复杂度。
def two_add(target, nums):
"""
排序n(nlog(n)),然后两个指针往中间走(n),一共n(log(n))。
:param target:
:param nums:
:return:
"""
org_nums = {}
count = 0
for i in nums:
if org_nums.get(i) != None:
a = []
a.append(org_nums[i])
a.append(count)
org_nums[i] = a
else:
org_nums[i] = count
count += 1
result_nums = []
sort_array_num = sorted(nums)
point_a = 0
point_b = len(sort_array_num) - 1
if len(sort_array_num) < 2:
print("input is wrong")
else:
while True:
if sort_array_num[point_a] + sort_array_num[point_b] == target:
break
elif sort_array_num[point_a] + sort_array_num[point_b] > target:
point_b -= 1
else:
point_a += 1
if sort_array_num[point_a] == sort_array_num[point_b]:
result_nums.append(org_nums[sort_array_num[point_a]][0])
result_nums.append(org_nums[sort_array_num[point_a]][1])
else:
result_nums.append(org_nums[sort_array_num[point_a]])
result_nums.append(org_nums[sort_array_num[point_b]])
return result_nums
方法二(自己实现,40ms):
思路:使用dict记录:key为目标值减去当前值,value为索引值。每次循环判断,如果当前值存在dict中,则表明找到这两个数了。dict使用hash实现的,理论上时间复杂度为O(1),同时循环一次时间复杂度为O(n)。总的时间复杂度为O(n)。
def two_add(nums, target):
"""
:param nums:
:param target:
:return:
"""
record_need_num = {}
count = 0
result = []
for num in nums:
if record_need_num.get(num) != None:
result.append(record_need_num.get(num))
result.append(count)
break
record_need_num[target - num] = count
count += 1
return result
java实现
方法一(查看,15ms):
思路:暴力破解,即两个for循环,时间复杂度为O(N^2)。
private int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
方法二(自己实现,5ms):
思路:与python方法二原理相同。
private int[] twoSumMap(int[] nums, int target) {
int[] result = {0, 0};
Map<Integer, Integer> recordMap = new HashMap<Integer, Integer>();
int count = 0;
for (int num : nums){
if(recordMap.containsKey(num)){
result[0] = recordMap.get(num);
result[1] = count;
return result;
}
else{
recordMap.put(target - num, count);
}
count += 1;
}
throw new IllegalArgumentException("No two sum solution");
}