LeetCode--Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Code Example:
1 public static int[] twoSum(int[] nums, int target) { 2 int[] k = new int[nums.length]; 3 for (int index = 0; index < nums.length - 1; index++) { 4 for (int index2 = 1; index2 < nums.length; index2++) { 5 int j = nums[index] + nums[index2]; 6 if (j == target && index != index2) { 7 for (int m = 0; m < k.length - 1; m++) { 8 k[m] = index; 9 k[m + 1] = index2; 10 } 11 } 12 } 13 } 14 return k; 15 } 16 public static void main(String[] args) { 17 int[] nums = {2, 5, 5, 11, 8}; 18 int[] ret = twoSum(nums, 10); 19 for (int m = 0; m < ret.length - 1; m++) { 20 System.out.println("[" + ret[m] + "," + ret[m + 1] + "]"); 21 } 22 }
llh