LeetCode #001 Two Sum

LeetCode #001 Two Sum

原题链接:https://leetcode.com/problems/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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

Subscribe to see which companies asked this question

解题思路

原始思路:遍历数组,取target与每次遍历的值作差,在数组中剩余的值里寻找差值。

代码原始思路:嵌套循环遍历数组,查看两次遍历的数值和是否和target相等,时间复杂度O(N^2)

注意点:因为在内外层循环中同一个数只能使用一次,所以要保证内外层循环使用的数值不同。

改进思路:   这里我使用下标间隔internal来实现。

                    通过计算nums[i]+nums[i+internal],来求和。外层循环使用internal递增(有点类似希尔排序或者分治法的思想)。

                    如nums中有10个数,下标1,2,3....10

                    外循环第一次作和:[0]+[1],[1]+[2],[2]+[3],[3]+[4],...,[8]+[9]

                              第二次作和:[0]+[2],[1]+[3],[2]+[4],[3]+[5].....[7]+[9]

                              ............

                              第10次作和:[0]+[9]

具体代码:

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		int internal = 1;
		for (internal = 1; internal <nums.size(); internal++) {
			for (int j = 0; j < (nums.size()-internal);j++){
				if ((nums[j+internal] + nums[j]) == target) {
					vector<int> result = {j,j+internal};
					return result;
				}

			}
		}
	}
};
不过有一点疏漏的是,没有考虑到如果存在大量冗余数据的话,会重复遍历和输出相同的组合,具体讨论见 LeetCode #015 3Sum

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值