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];
        }
    }
    
  • 相关阅读:
    NodeJs 的Module.export 和 export
    Angular 调试
    设计模式 -- 访问者
    typescript 枚举
    Swagger 实践 <二>
    eventFlow 系列 <三> 查询所有
    成员变量的隐藏和方法的重写
    Facetoprocess_program_design
    ATM_tests
    transmission protocol
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13764294.html
Copyright © 2011-2022 走看看