Leet Code OJ 1. Two Sum [Difficulty: Easy]

题目:
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].

翻译:
给定一个整形数组和一个整数target,返回2个元素的下标,它们满足相加的和为target。
你可以假定每个输入,都会恰好有一个满足条件的返回结果。

Java版代码1(时间复杂度O(n)):

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map map=new HashMap<>();
        for(int i=0;iget(target-nums[i]);
            if(index==null){
                map.put(nums[i],i);
            }else{
                return new int[]{i,index};
            }
        }
        return new int[]{0,0};
    }
}

Java版代码2(时间复杂度O(n^2)):

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result=new int[2];
        for(int i=0;i1;i++){
            for(int j=i+1;jif(nums[i]+nums[j]==target){
                    return new int[]{i,j};
                }
            }
        }
        return result;
    }
}

你可能感兴趣的:(算法题解,每周一道算法题,数组,LeetCode,算法)