LeetCode 1: two numbers and Two Sum

topic:

Given an array of integers numsand a target value target, and you find that the target value in the array of two integers, 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.

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:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

Problem-solving ideas:

  • Brute force: the outer loops through each element x, the inner loop to find out if there is a value target - xequal to the target element, returns the index of the target elements are equal and x. Time complexity of O (n ^ 2), the efficiency is too low, pass.

  • Hash: hash map (map, dict), key save the element, value save the element index.

    • Two traversal method: The first time through the preservation of all the elements and their indexes to hash map, the second pass lookup target - xequal the target element

    • A traversal method: If y = target - x, then x = target -y, the time saved while traversing the hash map to find whether there is a value target - xequal to the target element.

      例:nums = [2, 11, 7, 15], target = 9, hashmap = { }
      遍历:
      i = 0: target - x = 9 - 2 = 7, 7 不存在于 hashmap 中,则 x(2) 加入 hashmap, hashmap = {2 : 0}
      i = 1: target - x = 9 - 11 = -2, -2 不存在于 hashmap 中,则 x(-2) 加入 hashmap, hashmap = {2 : 0, 11 : 1}
      i = 2: target - x = 9 - 7 = 2, 2 存在于 hashmap 中,则返回列表 [2, 0]

Code:

Two traversal (Java):

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {//一次遍历转换成键值对,key为元素值,value为索引值
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {//二次遍历查找符合条件的元素
            int res = target - nums[i];
            if (map.containsKey(res) && map.get(res) != i) {//查找到的目标元素不能为其本身
                return new int[]{i, map.get(res)};
            }
        }
        return null;
    }
}

Once traversal (Java):

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int res = target - nums[i];
            if (map.containsKey(res)) {//因为自身元素还未加入到 hashmap,无需 map.get(res) != i 条件判断
                return new int[]{i, map.get(res)};
            }
            map.put(nums[i], i);//未找到目标元素则将其加入 hashmap
        }
        return null;
    }
}

A traverse (Python):

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i, num in enumerate(nums): #枚举 nums 数组
            if num in dic:
                return [dic[num], i]
            else:
                dic[target-num] = i

Python comes with an array of index use problem-solving method:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i, num in enumerate(nums):
            if target-num in nums and nums.index(target-num) != i:
                return [i, nums.index(target-num)]

list.index():

description:

index () function is used to find the location of an index value of the first match from the list.

grammar:

index () method syntax:

list.index(x, start, end)

parameter:

  • x-- objects to find.
  • start-- optional, to find the starting position.
  • end-- optional end position to find.

return:

This method returns the index to find the location of the object, if the object is not found exception is thrown.

Welcome attention to micro-channel public number:... Love to write Bug
I love to write Bug.png

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/11687832.html