LeetCode 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, 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].


暴力解法(Java):

1 class Solution {
2     public int[] twoSum(int[] nums, int target) {
3         for(int i=0;i<nums.length;i++)
4             for(int j=i+1;j<nums.length;j++)
5                 if(nums[i]+nums[j]==target)
6                     return new int[]{i,j};
7         return new int[]{0,0};
8     }
9 }

利用hashset,遍历nums,若在set中找到一个值与当前值相加为target,则返回两个下标,否则将当前值加入set(Java):

class Solution {
    public int[] twoSum(int[] nums, int target) {
        
        Set<Integer> set = new HashSet<>();
        int i=0;
        int j=0;
        
        for(i=0;i<nums.length;i++)
        {
            if(set.contains(target-nums[i])) 
                break;
            else
                set.add(nums[i]);
        }
        
        while(nums[j]!=target-nums[i])
            j++;
        
        return new int[]{j,i};
    }
}
原文地址:https://www.cnblogs.com/trymorel/p/12520917.html