Leetcode simple algorithm-simple (the sum of two numbers)One

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

Given nums = [2, 7, 11, 15], target = 9 because nums[0] + nums[1] = 2 + 7 = 9. So return [0, 1]

class Solution {
    
    
   public int[] teoSun(int[] nums,int target){
    
    
   		HasnMap<Integer,Integer> map = new HashMap<>();
   		for(int i = 0;i<nums.length;i++){
    
    
			int num = target - nums[i];
			if(map.containskey(num)){
    
    
				return new int[]{
    
    map.get(num),i};
			}
			map.put(nums[i],i);
		}
		return null;
   }
}

Considering the time and space complexity, you can use the violent problem-solving method, that is, double for loop, traversal comparison, but the time complexity is O(n^2), and the time complexity of the above method is O(n).
The idea is as follows: sequentially traverse a number num1, and use target-num1 to find whether there is this number in the array. Return if there is.

Guess you like

Origin blog.csdn.net/A_Tu_daddy/article/details/103563049