Leetcode-Two Sum

来源:互联网 发布:成都真那么好么知乎 编辑:程序博客网 时间:2024/06/07 15:48

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

AC代码:

import java.util.Arrays;class Pair implements Comparable<Pair>{int val;int index;public Pair( int val, int index ){this.val = val;this.index = index;}@Overridepublic int compareTo(Pair other) {// TODO Auto-generated method stubreturn this.val - other.val;}}public class Solution {      public int[] twoSum(int[] numbers, int target){int result[] = new int[2];//store indexint index[] = new int[numbers.length];//relate number and indexPair pairs[] = new Pair[numbers.length];for( int i=0; i<numbers.length; i++){pairs[i] = new Pair(numbers[i],i+1);}//1 sortArrays.sort(pairs);//2 find index int pre = 0, last = numbers.length-1;while( pre < last ){if( pairs[pre].val + pairs[last].val == target ){if( pairs[pre].index < pairs[last].index){result[0] = pairs[pre].index;result[1] = pairs[last].index;}else{result[0] = pairs[last].index;result[1] = pairs[pre].index;}break;}else if( pairs[pre].val + pairs[last].val < target){pre++;}else if( pairs[pre].val + pairs[last].val > target ){last--;}}return result;    }  }  



超时代码(时间复杂度O(n*n)):

public int[] twoSum(int[] numbers, int target){int result[] = new int[2];for( int i=0; i<numbers.length; i++ ){for( int j=i+1; j<numbers.length; j++){if( numbers[i]+numbers[j] == target ){result[0] = i+1;result[1] = j+1;break;}}}return result;}


0 0
原创粉丝点击