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

Solution

這題是hashmap or set的初級運用。透過map or set尋找之前出現過符合條件的數字就可以

T : O(n)

 public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int a = 0, b = 0;
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target-nums[i])){
                b = i;
                a = map.get(target-nums[i]);
                break;
                 
            }
            map.put(nums[i], i);
        }
        return new int[]{a,b};
        
    }

Last updated

Was this helpful?