zoukankan      html  css  js  c++  java
  • LeetCode 1 两数之和

    LeetCode 1 两数之和

    问题描述:
    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    哈希表: O(N)
    使用哈希表记录下数组中值与下标的对应关系
    使用哈希表快速查找数组中是否存在某个值

    执行用时:3 ms, 在所有 Java 提交中击败了74.60%的用户
    内存消耗:38.8 MB, 在所有 Java 提交中击败了85.02%的用户

    class Solution {
        public int[] twoSum(int[] nums, int target) {
        	Map<Integer,Integer> map = new HashMap<>();
        	/*导入哈希表*/
        	for(int i=0;i<nums.length;i++) {
        		map.put(nums[i], i);
        	}
        	for(int i=0;i<nums.length;i++) {
        		int complement = target - nums[i];
        		if(map.containsKey(complement) && map.get(complement)!=i) {
        			return new int[] {i,map.get(complement)};
        		}
        	}
        	return new int[0];
        }
    }
    
  • 相关阅读:
    luogu P3834 【模板】可持久化线段树 1(主席树) 查询区间 [l, r] 内的第 k 小/大值
    覆盖的面积 HDU
    Picture POJ
    Atlantis HDU
    Transformation HDU
    Tunnel Warfare HDU
    Agri-Net POJ
    Conscription POJ
    Brush (IV) LightOJ
    Throwing Dice LightOJ
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13764294.html
Copyright © 2011-2022 走看看