# Leetcode 1. Two Sum (java)

2018-03-02 08:31:37来源:cnblogs.com作者:CyanChan人点击

`class Solution {    public int[] twoSum(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                if( nums[i] + nums[j] == target ){                    int[] result = new int[2];                    result[0] = i;                    result[1] = j;                    return result;                }            }        }        return null;    }}`

`class Solution {    public int[] twoSum(int[] nums, int target) {        Hashtable<Integer,Integer> map = new Hashtable<Integer,Integer>();        for (int i = 0; i < nums.length; i++) {            map.put(nums[i],i);        }        for (int i = 0; i < nums.length; i++) {            int another = target - nums[i];　　　　　　　//过滤元素本身            if( map.get(another) != null &&map.get(another) > i ){                int[] result = new int[2];                result[0] = i;                result[1] = map.get(another);                return result;            }        }        return null;    }}`

github地址：https://github.com/CyanChan/Leetcode-Record

无相关信息