Day07-06_13【CT】LeetCode手撕—1. 两数之和-3- ACM实现

public class twoSum {

    public static int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];

        // 哈希表
        Map<Integer,Integer> map = new HashMap<>();
        // 存 key 值 ——> value 下标


        // 遍历数组
        for(int i  = 0 ; i < nums.length ;i++){
            if(map.containsKey(target-nums[i])){
                res[0] = i;
                res[1] = map.get(target-nums[i]);
            }
            map.put(nums[i],i);
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数组长度");
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0 ; i < n;i++){
            nums[i] = sc.nextInt();
        }
        System.out.println("输入目标和");
        int target = sc.nextInt();
        int[] forRes = twoSum(nums,target);
        for(int i : forRes){
            System.out.print(i+" ");
        }
    }
}
上一篇:数据库漫谈-MongoDB


下一篇:CS5518芯片设计|替代GM8775设计方案|MIPI转LVDS芯片方案|DSI转LVDS芯片方案