LeetCode-Two Sum(编程之美-快速寻找满足条件的两个数字)

61 篇文章 10 订阅
7 篇文章 0 订阅

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

最直观的办法,暴力破解法:

public int[] twoSum1(int[] numbers, int target) {
    	int[] result = new int[2];
        for (int i = 0; i < numbers.length; i++) {
        	for (int j = i+1; j < numbers.length; j++) {
        		if (target == numbers[i]+numbers[j]) {
        			result[0] = i+1;
        			result[1] = j+1;
        			return result;
        		}
        	}
        }
		return result;
    }

很显然,超时。分析上述代码,外层循环是必须的,但是内层循环主要为了找到匹配的值,如果能在O(1)的复杂度找到target-numbers[i]的值即可,于是肯定要使用HashTable;自己的代码:

public int[] twoSum(int[] numbers, int target) {
    	Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    	int[] result = new int[2];
    	for (int i = 0; i < numbers.length; i++) {
    		map.put(numbers[i], i+1);
    	}
    	for (Integer value : map.keySet()) {
    		Integer index2 = map.get(target-value);
    		if (index2 != null) {
    			int index1 = map.get(value);
    			if (index1 < index2) {
    				result[0] = index1;
    				result[1] = index2;
    			} else if (index1 == index2) {
    				for (int i = 0; i < numbers.length && index1 != i+1; i++) {
    					if (numbers[i] == value) {
    						result[0] = i+1;
    	    				result[1] = index1;
    	    				break;
    					}
    				}
    			} else if (index1 > index2) {
    				result[0] = index2;
    				result[1] = index1;
    			} 
    			return result;
    		}
    	}
		return result;
    }

代码比较好懂,但是也比较臃肿。第一个for循环,往hash表里放值。第二个循环就有很多问题,因为如果出现{0,2,3,0} target=0的测试用例时,会发现hash表里只是存储了一个0。另外一个又查找了一遍,很是蛋疼。下面又做了修改:

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

这种代码很巧妙,尤其是第二个循环,可想而知,从前往后遍历,因为是成对出现的,而如果出现上述情况,显然为<3,3>,而遍历是从头开始的,所以也很容易知道哪个index比较小。在优化一下,把两个for循环合并成一个:

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

多思考,多优化,多总结!!!





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值