Leetcode[1] Two Sum

Givenan array of integers, find two numbers such that they add up to a specifictarget number

Thefunction twoSum should return indices of the two numbers such that they addup to the target, where index1must be less than index2. Please note that your returned answers (bothindex1 and index2) are notzero-based.

Youmay assume that each inputwould have exactly one solution.

Input:   numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

思路:构建一个hashtable,将2,7,11,15被9减去的值,作为key进行保存(value存index1的索引值),然后遍历一遍数组看有没有一个key就可以. 

考点:Map,Vector


JAVA版:


第一版 446MS bug free

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap();
        for(int i = 0; i < nums.length; i++){
            int key = target - nums[i];
            map.put(key, i+1);
        }
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                int index = i+1;
                if(index == map.get(nums[i]))
                    continue;
                return new int[]{index<map.get(nums[i])?index:map.get(nums[i]), index>map.get(nums[i])?index:map.get(nums[i])};
            }
        }
        return null;
    }
}

第二版 369MS

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            int x = numbers[i];
            if (map.containsKey(target - x)) {
                return new int[] { map.get(target - x) + 1, i + 1 };
            }
            map.put(x, i);
        }
        return null;
    }
}


C++版本:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    	map<int,int> compareMap;
    	map<int,int> compareMap2;
		vector<int>::iterator iter=numbers.begin();
		vector<int> result;
		int count = 1;
		int length = numbers.size();
		for(int i = 0; i < length; ++i)  
                <span style="white-space:pre">	</span>compareMap[numbers[i]] = i;
		
		vector<int>::iterator iter2=numbers.begin();
		int index1 = 1;
		map<int,int>::iterator it = compareMap.end();  ///
		while (iter2 != numbers.end()){  

			it = compareMap.find(target - *iter2);
			if (it != compareMap.end()){
				int index2 = it->second+1;
				if (index1==index2){
					iter2++;
					index1++;
					continue;
				}
				result.push_back(index1);
				result.push_back(index2);
				break;
			}
			index1++;
			iter2++;  
		}
		return result;
    }
};



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值