leetcode_java_twosum

来源:互联网 发布:三星淘宝账号出售 编辑:程序博客网 时间:2024/06/15 07:17

问题:

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

Subscribe to see which companies asked this question


自己的代码:

import java.util.Arrays;public class MainTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint a[]={0,4,3,0};int target = 0;int result[] = twoSum(a,target);System.out.print(result[0]+" "+result[1]);}public static int[] twoSum(int[] nums, int target) {int[] result = new int[2];int[] array = nums.clone();int[] sequence = new int[2];int error = -1;Arrays.sort(nums);if(nums.length>1){for(int i=0;i<nums.length-1;i++){result[1]=Arrays.binarySearch(nums,i+1,nums.length,target-nums[i]);error = result[1];if(result[1]>=i){result[1]=target-nums[i];result[0]=nums[i];break;}}if(error<0){sequence[0]=-1;sequence[1]=-1;}else{/* * 以下方法错误 *///sequence[0]=Arrays.binarySearch(array, result[0]);//sequence[1]=Arrays.binarySearch(array, result[1]);/* * 以下方法同样不正确 *///for(int i=0;i<array.length;i++){//if(array[i]==result[0]){//sequence[0]=i+1;//}else if(array[i]==result[1]){//sequence[1]=i+1;//}//}/* * 以下方法正确 */for(int i=0;i<array.length;i++){if(array[i]==result[0]){sequence[0]=i+1;break;}}for(int i=0;i<array.length;i++){if(array[i]==result[1]){sequence[1]=i+1;}}if(sequence[0]>sequence[1]){int tmp = sequence[0];sequence[0]=sequence[1];sequence[1]=tmp;}}}else{//输入数据有误}return sequence;    }}

刷第一道题的过程中,自己犯了一些错误:

1、没有考虑到可能两个数相等的情况。

2、binarySearch输入必须是有序的。


另外,Arrays.binarySearch(arg0,fromIndex,toIndex,target) 是在arg0[fromIndex,...,toIndex-1]中进行搜索。


0 0
原创粉丝点击