[Algorithm-Java implementation] The sum of two numbers

[Algorithm-Java implementation] The sum of two numbers

1. Problem description:

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

Source of this question: Likou 1

2. Question answer:

Solution 1: Violence

Double-layer for loop traverse, judge whether the addition of two numbers is target

The second number can only be the number after the first number, so the second level of for loop starts from the subscript i+1

code show as below

class Solution {
    
    
    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[i]+nums[j]==target){
    
    
                    return new int[]{
    
    i,j};
                }
            }
        }
        return new int[0];
    }
}

Analysis of Algorithms:

Time complexity: O(N squared)

Space complexity: O(1)

Solution 2: Hash table

Create a HashMap, the key is nums[i], the value is i, so that you can get the value based on the key through the get() method

Use the put() method to store the nums[i] and i of the array as key-value pairs in HashMap.

During for loop traversal, int otherNum=target-nums[i], judge whether otherNum exists in the key of HashMap, and return the corresponding array subscript if it exists.

code show as below

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

note: Map.put(nums[i],i) This method should be after the if judgment

If the test case is nums=[3,2,4],target=6, it will return [0,0], and the result is not satisfied [1,2]

Because if you put() first and then if judgment, when judgment is just otherNum=6-3=3, it will return two 0 subscripts, which means that the same number is used twice, which does not meet the conditions of the question.

Insert picture description here

Analysis of Algorithms

Time complexity: O(N): for loop traversal, N is the number of elements in the array

Space complexity: O(N): Create a hash table to store the value of the array, N is the number of elements in the array

Guess you like

Origin blog.csdn.net/hkdhkdhkd/article/details/111657038