LeetCode刷题笔录 Two Sum

LeetCode Two Sum 解题策略与Java实现
这篇博客主要探讨了LeetCode中的Two Sum问题,要求找到数组中两数之和等于目标值的下标,且index1 < index2。作者首先提出复制并排序原数组,然后通过线性搜索找到目标值的解决方案,时间复杂度为O(nlogn)。注意到当两个数相同时,返回不同的下标。此外,还提及了一个使用HashMap实现的O(n)时间复杂度的优化算法。

Two Sum

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.

思路:

先把原数组复制一遍,然后进行排序。在排序后的数组中找这两个数。最后再在原数组中找这两个数字的index即可。

时间复杂度O(nlogn)+O(n)+O(n) = O(nlogn)

注意的是结果有可能是两个数是相同的,比如 0 3 4 0, 0要返回1和4,不要返回成1和1或者4和4.

代码:

	public int[] twoSum(int[] numbers, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
		
		//Copy the original array and sort it
		int N = numbers.length;
		int[] sorted = new int[N];
		System.arraycopy(numbers, 0, sorted, 0, N);
        Arrays.sort(sorted);
        //find the two numbers using the sorted arrays
        int first = 0;
        int second = sorted.length - 1;
        while(first < second){
        	if(sorted[first] + sorted[second] < target){
        		first++;
        		continue;
        	}
        	else if(sorted[first] + sorted[second] > target){
        		second--;
        		continue;
        	}
        	else break;
        }
        int number1 = sorted[first];
        int number2 = sorted[second];
        //Find the two indexes in the original array
        int index1 = -1, index2 = -1;
        for(int i = 0; i < N; i++){
        	if((numbers[i] == number1) || (numbers[i] == number2)){
        		 if(index1 == -1)
        			 index1 = i + 1;
        		 else
        			 index2 = i + 1;
        	}
        		
        }
        int [] result = new int[]{index1, index2};
        Arrays.sort(result);
		return result;
    }

还有个无耻地利用hashmap的O(n)的算法,原理和暴力搜索没有本质区别,只不过hashmap的搜索速度是O(1)。

public int[] twoSum(int[] numbers, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		int n = numbers.length;
		int[] result = new int[2];
		for (int i = 0; i < numbers.length; i++)
        {
            if (map.containsKey(target - numbers[i]))
            {
                result[0] = map.get(target-numbers[i]) + 1;
                result[1] = i + 1;
                break;
            }
            else
            {
                map.put(numbers[i], i);
            }
        }
		return result;
        
    }




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值