问题描述
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].
解法
public class Solution { public int[] twoSum(int[] nums, int target) { int[] rst = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { rst[0] = i; rst[1] = j; break; } } } return rst; }}遍历数组求和,此法需遍历2次,使用HashMap好像只需要遍历一次,日后补上。
测试
public static void main(String[] args) { int[] i = {2, 7, 11, 15}; int[] rst = new int[2]; Solution sl =new Solution(); rst = sl.twoSum(i, 22); System.out.PRintln(rst[0]); System.out.println(rst[1]); }