LeetCode 1: two numbers

topic:

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:
Given nums = [2, 7, 11 , 15], target = 9
because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]

1 violent problem-solving ideas

Time complexity: O (n ^ 2)
For each element, we try to find the target element corresponding to the rest of it through the array, which will take O (n) O (n) time. Thus the time complexity is O (n ^ 2).
Complexity Space: O (1).

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 };
                    }
                }
            }
            return new int[0];
        }

2 idea by hashmap

Time complexity: O (n),
we only have to traverse the list contains n elements once. Carried out in each table lookup only takes O (1) time.
Space complexity: O (n),
the additional space required depends on the number of elements stored in the hash table, the table needs to store up to n elements.

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

leetCode link two numbers

Published 80 original articles · won praise 140 · views 640 000 +

Guess you like

Origin blog.csdn.net/linjpg/article/details/104564401