LeetCode 之 Two Sum

来源:互联网 发布:mac ssh 编辑:程序博客网 时间:2024/05/17 07:51

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

分析 : 先将数组copy , 然后排序, 对排序后的数组做查找。定义两个指针, left 和right, 一个从左往右, 一个从右往左。 找到之后在从原数组中找index。

public static boolean soluction(int[] arry_int, int target){int left = 0;int right = arry_int.length - 1;int sum = 0;int leftNum = 0;int rightNum = 0;int[] arry_int_copy = arry_int.clone();Arrays.sort(arry_int);if(target<arry_int[0])return false;while(left <  right){sum = arry_int[left] + arry_int[right];if(sum == target){System.out.println(left + "/" + right);leftNum = arry_int[left];rightNum = arry_int[right];int index = 0;for(index = 0 ; index < arry_int_copy.length ; index ++){if(leftNum == arry_int_copy[index]){left = index;}if(rightNum == arry_int_copy[arry_int_copy.length-1-index]){right = arry_int_copy.length -1 -index;}}System.out.println(right+"/"+left);return true ;}if(sum<target){left = left + 1;}if(sum > target){right = right - 1;}}return false;}


0 0
原创粉丝点击