⚡️Algorithm practice~array-sum of two numbers~⚡️

topic description

Given an array of integers, please find two numbers in the array that add up to the target value. The function twoSum you give needs to return the subscripts (index1, index2) of these two numbers, and it needs to satisfy that index1 is less than index2. Note: The subscript starts from 1.
Assume that there is only a unique solution in the given array
. For example: the given array is {20, 70, 110, 150}, and the target value is 90. Output index1=1, index2=2

Solution 1

Simple and crude, double-layer loops are added for comparison. This is the easiest way to think of, enumerate each number x in the array, and find out whether target - x exists in the array

import java.util.*;


public class Solution {
    
    
    /**
     * 
     * @param numbers int整型一维数组 
     * @param target int整型 
     * @return int整型一维数组
     */
    public int[] twoSum (int[] numbers, int target) {
    
    
        // write code here
        int [] result = new int[2];
        for (int i = 0; i < numbers.length ;i++){
    
    
            if(numbers[i] > target) continue;
            for(int j = 0; j < numbers.length ; j++){
    
    
                if(numbers[i] + numbers[j] == target && i < j){
    
    
                    result[0] = i + 1;
                    result[1] = j + 1;
                    return result;
                }
            }
        }
        return result;
    }
}

Complexity Analysis

Time complexity: O(N^2) where N is the number of elements in the array. In the worst case, any two numbers in the array must be matched once.
Space complexity: O(1).

Solution 2

Borrowing map for processing
The reason for the high time complexity of Solution 1 is that the time complexity of finding target - x is too high. Therefore, we need a method that can quickly find whether the target element exists in the array. If it exists, we need to find out its index. Using a hash table, the time complexity of finding target - x can be reduced from O(N) to O(1).

public static int[] twoSum (int[] numbers, int target) {
    
    
        int [] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length ;i++){
    
    
            if(map.get(target - numbers[i]) != null){
    
    
                result[0] = map.get(target - numbers[i]) + 1;
                result[1] = i + 1;
                return result;
            }
            map.put(numbers[i],i);
        }
        return result;
    }

Topic Link:
Sum of Two Numbers

Guess you like

Origin blog.csdn.net/weixin_43863054/article/details/120304540