`
liubangchuan
  • 浏览: 15635 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

LeetCode Problem:在一个数组中求满足和等于一定条件的两个数

 
阅读更多

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

 

这个题目编程之美上面也提到了,不过这里的要求是要返回值在序列中的索引

 解法一:

借助于哈希表,时间复杂度为O(n),空间复杂度最坏情况下O(n),代码是java语言

	public static int[] twoSumByHash(int[] numbers, int target){
		if(numbers == null || numbers.length < 2){
			return new int[]{-1,-1};
		}
		Map<Integer,Integer> map = new HashMap<Integer,Integer>();
		map.put(target - numbers[0], 0);
		for(int i=1;i<numbers.length;i++){
			if(map.keySet().contains(numbers[i])){
				return new int[]{map.get(numbers[i])+1,i+1};
			}else{
				map.put(target - numbers[i], i);
			}
		}
		return new int[]{-1,-1};
	}

 解法二:

先排序,然后从两头遍历,时间复杂度为O(n)

public static int[] twoSum(int[] numbers, int target) {
		int[] nums = numbers.clone();
		Arrays.sort(numbers);
		int i = 0;
		int j = numbers.length - 1;
		while(i<j){
			if(numbers[i] + numbers[j] == target){
				break;
			}else if (numbers[i] + numbers[j] < target){
				i++;
			}else{
				j--;
			}
		}
		if(i< j ){
			int[] result = new int[2];
			int count = 0;
			for(int k=0;k<nums.length;k++){
				if(nums[k] == numbers[i] || nums[k] == numbers[j]){
					result[count++]=k+1;
				}
			}
			return result;
		}

		return new int[]{-1,-1};
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics