[Java] [Advanced] Return array subscript

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

package com.itheima;
import java.util.*;
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int nums[] = {
    
    1,4,5,6,7,9,76,43,22,11};
        int target = 11;
        int result[] = twoSum(nums,target);
        for (int i=0;i<result.length;i++){
    
    
            System.out.println(result[i]);
        }



    }
    static int[] twoSum(int [] nums,int target){
    
    
        int temp[] = new int [2];
        int t;
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
    
    
            t = nums[i];
            if(map.containsKey(target - t)){
    
    
                temp[0] = i;
                temp[1] = map.get(target-t);
                return temp;
            }else {
    
    
                map.put(t,i);
            }
        }
        return null;
    }



}

Guess you like

Origin blog.csdn.net/weixin_48180029/article/details/112972613