`

LeetCode [1] 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.

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

 

public static int[] twoSum2(int[] nums, int target) {
		int[] result = new int[2];
		int length = nums.length;
		int[] tempNums = nums.clone();
		sortit(tempNums, 0, length -1);
		result[0] = 0;
		result[1] = 0;
		int min = 0;
		int max = length -1;
		boolean find = false;
		while(min < max && !find){
			if((tempNums[min] + tempNums[max]) > target){
				max--;
			}else if((tempNums[min] + tempNums[max]) < target){
				min++;
			}else{
				find = true;
			}
		}
		
		if(find){
			for(int i = 0; i < length; i++){
				if(tempNums[min] == nums[i]){
					result[0] = i + 1;
					break;
				}
			}
			
			for(int i = 0; i < length; i++){
				if(tempNums[max] == nums[i]){
					if(tempNums[max] == tempNums[min] && (result[0]==(i+1)) ){
						continue;
					}
					result[1] = i + 1;
					break;
				}
			}
		}
		
		if(result[0] > result[1]){
			int j = result[0];
			result[0] = result[1];
			result[1] = j;
		}
		
		return result;
    }
	
	
	private static void sortit(int[] list, int left, int right){
		if(left< right){
			int middle = partition(list, left, right);
			sortit(list, left, middle-1);
			sortit(list, middle+1, right);
		}
	}

	private static int partition(int[] list, int left, int right) {
		int privot = list[left];
		while(left < right){
			while(left < right && privot <= list[right]){
				right--;
			}
			list[left] = list[right];
			while(left < right && privot >= list[left]){
				left++;
			}
			list[right] = list[left];
		}
		list[left] = privot;
		
		return left;
	}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics