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.


分析

1 两种复杂度 用map key存值,val存索引, 这样的复杂度是o(n)

   循环遍历两次 o(n2)的复杂度


代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int array[] = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();//time o(n)
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                array[0] = map.get(target - nums[i]);
                array[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return array;
    // throw new IllegalArgumentException("No two sum solution");
    }
}

猜你喜欢

转载自blog.csdn.net/vvnnnn/article/details/80061983