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 class Solution {

	public int[] twoSum(int[] numbers, int target) {

		int[] result = new int[2];
		int temp1 = 0;
		int temp2 = 0;
		for (temp1 = 0; temp1 < numbers.length - 1; temp1++) {
			
			for (temp2 = temp1 + 1; temp2 < numbers.length; temp2++) {
                    if(numbers[temp1]+numbers[temp2]==target){
                    	result[0]=temp1+1;
                    	result[1]=temp2+1;
                    	break;
                    }
			}
			

		}
		return result;

	}
	

}

这个不算是最好的,希望大家告诉我又没有跑的更快的程序,谢谢

你可能感兴趣的:(SUM)