【Leetcode】001 Two Number

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].


读完题首先想到的就是两层遍历法,但是显然时间复杂度太高,是O(N^2),不符合要求,于是就应该想如何降低复杂度,首先应该想将逐个比较转变为直接查找,即首先计算出 target与当前元素的差,然后在序列中寻找这个差值,这样首先就把问题简化了,而寻找的过程可以先对序列进行快排,然后二分查找,这样整体的复杂度就降低为 O(N*logN) 了;查找最快的方法是利用一个 map容器存储每个元素的索引,这样取得某个特定元素的索引只需要常数时间即可完成,这样就更快了,最多只需遍历一次序列,将元素及其索引加入map中,在遍历的过程中进行对应差值的查找,如果找到了就结束遍历,这样时间复杂度最多为 O(N),It's amazing!

方法一:双层循环遍历

 public static int[] twoSum(int[] nums, int target) {
    	if(nums == null){
    		return null;
    	}
        int len = nums.length;
        for (int i = 0; i < len; i++){
            for (int j = i + 1; j < len; j++){
                if(nums[i] + nums[j] == target){
                	return new int[]{i, j};
                }
            }
        }
        return null;
    }

方法二:排序后双向逼近

public static int[] twoSum(int[] nums, int target) {
    	if(nums == null){
    		return null;
    	}
    	int len = nums.length;
    	int[] newnums = Arrays.copyOf(nums, len), result = new int[2];
    	Arrays.sort(newnums);		
    	
    	int low = 0, high = len - 1, result0 = 0, result1 = 0;
    	while (low < high) {
			if (newnums[low] + newnums[high] < target) {
				low++;
			}else if (newnums[low] + newnums[high] > target) {
				high--;
			}else {
				result0 = newnums[low];
				result1 = newnums[high];
				break;
			}	
		}
    	
    	for (int i = 0; i < len; i++) {
			if (nums[i] == result0) {
				result[0] = i;
			}else if (nums[i] == result1) {
				result[1] = i;
			}
		}
    	return result;
    }


方法Map的Value-index方式

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值