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];
        }
    }
    
  • 相关阅读:
    栈和队列
    数组的遍历查找
    字符串的子串
    两个字符串
    字符串的遍历
    字符串的替换
    数组和矩阵
    Django 自带的ORM增删改查
    what's the CRSF ??
    Rabbitmq -Publish_Subscribe模式- python编码实现
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13764294.html
Copyright © 2011-2022 走看看