Two Sum算法


①算法描述:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解决方法:
   
一:使用java for循环,暴力搜索方式
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[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

二:使用Hashmap,将时间复杂度减小到O(n)

public class Solution
{
    public int[] twoSum(int[] nums, int target) 
    {
        Map map=new HashMap<>();
        
        for(int i=0;i


你可能感兴趣的:(算法,Two,sum算法)