标签:
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
1 package AddTwoNumbers; 2 3 public class addTwoNums { 4 5 public static int[] twoSum(int[] nums, int target) { 6 int[] indexArray = {1,1}; 7 int i = 0; 8 boolean flag = false; 9 while (i < nums.length) { 10 for (int j = i + 1; j < nums.length; j++) { 11 if((nums[i] + nums[j]) == target){ 12 indexArray[0] = i + 1; 13 indexArray[1] = j + 1; 14 flag = true; 15 break; 16 } 17 } 18 if (flag == true) 19 break; 20 i++; 21 } 22 23 if(indexArray[0] > indexArray[1]){ 24 int temp; 25 temp = indexArray[0]; 26 indexArray[0] = indexArray[1]; 27 indexArray[1] = temp; 28 } 29 30 return indexArray; 31 } 32 33 public static void main(String args[]){ 34 int[] nums = {11,4,3,2,1}; 35 int[] result = null; 36 result = twoSum(nums,6); 37 for (int i = 0; i < result.length; i++) { 38 System.out.println(result[i]); 39 } 40 } 41 }
标签:
原文地址:http://www.cnblogs.com/rustfisher/p/4639331.html