1. 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.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution One:使用两重循环解决
 1 public class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         int[] result = {0,1};
 4          for (int i = 0; i < nums.length-1; i++) {
 5              for (int j = i+1; j < nums.length; j++) {
 6                  if (nums[i] + nums[j]==target) {
 7                      result[0]=i;
 8                      result[1]=j;
 9                      return result;
10                  }
11              }
12          }
13          return result;
14     }
15 }




Solution Two:使用hashmap,把数组装入map中,把数组值定为key,小标定为value,然后对于数组中的每一个key,遍历去寻找其他key,满足相加可以等于target:

 1    public int[] twoSum(int[] numbers, int target) {
 2         Map<Integer,Integer> map = new HashMap<Integer, Integer>();
 3         for (int i=0;i<numbers.length;i++) {
 4             map.put(numbers[i], i);
 5         }
 6         for (int i=0;i<numbers.length;i++) {
 7             int dif = target-numbers[i];
 8             Integer index = map.get(dif);
 9               
10             if (index!=null && i!=index) {
11                 if (index>i)
12                     return new int[]{i,index};
13                 else
14                     return new int[]{index,i};
15             }
16         }
17           
18         return null;
19     }
20 }


 
原文地址:https://www.cnblogs.com/crazybuddy/p/5246886.html