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

    题目描述

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    示例:
    给定 nums = [2, 7, 11, 15], target = 9
    
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]
    
    考察点:

    哈希表、数组

    解法1(暴力枚举):

    解题思路:

    双重for循环,爽!!

    /*
    *执行用时:63 ms
    *内存消耗:39 MB
     */
    public class Solution {
            public  int[] twoSum(int[] nums, int target) {
                int[] res = new int[2];
                
                for (int i = 0; i < nums.length; i++) {
                    for (int j = i + 1; j < nums.length; j++){
                        
                        if (nums[i] + nums[j] == target) {
                            res[0] = i;
                            res[1] = j;
                            return res;
                        }
                       
                    }
                }
                return null;
            }
    
        }
    

    解法2(哈希表):

    解题思路:

    遍历一轮 nums 数组,先把数组里所有元素的值作为key,下标作为value存进map里,并在map中寻找是否有这个 元素 的键,其值即为 nums 数组中的下标

    /*
     *运行时间:2 ms
     *内存消耗:39.3 MB
     */
    
    public class Solution {
            public int[] twoSum(int[] nums, int target) {
    
                HashMap<Integer, Integer> map = new HashMap<>();	//创建辅助的哈希表
                int[] res = new int[2];		//用来存放结果的数组
    
                for (int i = 0; i < nums.length; i++) {			//遍历 nums 数组
                    int other = target - nums[i];			//差	
    
                    if (map.get(other) != null) {		//判断
                        res[0] = i;
                        res[1] = map.get(other);
                        return res;
                    }
    
                    map.put(nums[i],i);  	//填充
                }
    
                return res;
            }
    
  • 相关阅读:
    0603学术诚信和职业道德
    0602第二个冲刺
    0525《构建之法》8、9、10章读后感
    0525Sprint回顾
    实验三进程调度
    解决提问的问题
    阅读《构建之法》第13-17章
    阅读:第10、11、12章
    作业5.2(封装及测试)
    作业5.1
  • 原文地址:https://www.cnblogs.com/south-wood/p/13778646.html
Copyright © 2011-2022 走看看