Involved in the series of LeetCode brush questions: the sum of two numbers (simple)

Learn the algorithm, brush the force button, refuel the roll, enter the big factory!

Topic description

Link to topic

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target, and return their array indices.

You can assume that there will only be one answer for each input. However, the same element in the array cannot be repeated in the answer. You can return answers in any order.

Example 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]

Example 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

Example 3:

输入:nums = [3,3], target = 6
输出:[0,1]

hint:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • There will only be one valid answer

Involving knowledge points

There are many ideas for solving this problem. This article considers two problem solving ideas: brute force solution and the use of hash table;

For arrays we need to know the following:

  • An array is a collection of data of the same type stored in a contiguous memory space
  • Array subscripts start from 0
  • The addresses of the array in the memory space are contiguous

For the hash table we need to know the following:

  • The array is a simple hash table, where the key in the hash table is the index subscript of the array
  • The hash table can directly access the data according to the key code (can determine whether an element is in the set in O(1) time)

Then according to the title, we can extract the key points:

  • return array index
  • The same element in the array cannot be repeated in the answer
  • Array length is greater than or equal to 2

This is a simple problem. The first thing that comes to mind is the brute force method. The problem can be solved directly by using double for loops; but this will be very time-consuming, so the array at this time is not a very useful data structure. We can consider To the map of the hash table, it has the data structure of <key, value>, where the key is used to store the value, and the value is used to store the subscript where the array is located, that is, as we mentioned earlier, we can directly access it according to its key code. data, so that you can quickly find whether the target element and its corresponding subscript exist in the array.

Question answer

Java Problem Solution 1

Thought analysis

Directly use the double for loop to traverse the two arrays, then sum and compare with the target given by the question, but we need to pay attention that the question requires that the same element in the array cannot be repeated in the answer, so it is not natural to only use the array. It is easy to avoid this, so we use HashSet here to store the values ​​that satisfy the condition ( Introduction to HashSet ).

  • Create a HashSet to store values ​​that meet the conditions
  • Use a double for loop to traverse the two arrays, sum them, and put the values ​​that satisfy the conditions into a HashSet
  • Create an array, put the elements in the HashSet into the array

Code

class Solution {
    
    
    public int[] twoSum(int[] nums, int target) {
    
    

        Set<Integer> set = new HashSet<>(); //创建一个哈希表,用来存数满足条件的值
        //暴力解法:双重for循环
        for(int i = 0; i < nums.length - 1; i++){
    
     //求和的第一个元素
            for(int j = i + 1; j < nums.length; j++){
    
     //求和的第二个元素;遍历第一个元素后的元素
                if((nums[i]+nums[j]) == target){
    
     //如果两个元素和等于target,将其添加到哈希表中
                    set.add(i);
                    set.add(j);
                }
            }
    }
    int[] result = new int[set.size()]; //创建一个输出结果的数组
    int index = 0;

    for(int i : set){
    
     //遍历哈希表
         result[index] = i; //将哈希表中的元素放入数组
            index++;//数组后移一位
    }

    return result; //输出结果
    }
}

insert image description here

Java problem solution two

Thought analysis
The use of a hash table is an improvement on the previous method, because the two for loops in our previous method are very time-consuming, so this is a key improvement point. We use the map in the hash table to solve this problem. question. At this time, we only need to execute the for loop once to get the difference between the target and the array, and then directly check whether the map has the difference just now. If the conditions are met, put the corresponding subscript into the result array.

  • Create result array, hash table HashMap
  • Traverse the array to find the difference between the target and the array temp
  • Use the containsKey method of map to determine whether the condition is met, and if so, put it into the result array

Code

class Solution {
    
    
    public int[] twoSum(int[] nums, int target) {
    
    
        //使用map来解决,<key,value>;
        int[] result = new int[2]; //定义结果数组
        HashMap<Integer,Integer> map = new HashMap<>(); //定义HashMap

        for(int i = 0; i < nums.length; i++){
    
     //循环数组
            int temp = target - nums[i];    //用target减去数组中的值,得到临时temp
            if(map.containsKey(temp)){
    
      //看下map里面是否有temp(有的话就满足题目条件)
                result[1] = i; //将i值先放到结果数组中
                result[0] = map.get(temp); //将map中的temp赋给结果数组
            }
            map.put(nums[i],i); //使用put方法,将num[i]放到结果数组中(Map 集合中对应键名的键值对象)
        }
        return result;//输入结果
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44480968/article/details/123906878