zoukankan      html  css  js  c++  java
  • 1. Two Sum

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    此题给出一个一维数组,要求求出数组里面任意两个值的和为target的值,返回数组的两个索引值。
    姑且认为两个值分别用A,B代表,A+B=target,则A=target-B,这样我们就把两个变量变成了只含有一个变量B来解决。
    那么数据结构应该选择什么呢,这里用散列表,散列表(hashmap)是一种将键(key)映射为值(value)从而实现快速查找的数据结构,此题需要将题目数组的值作为散列表的键,将数组的索引作为散列表的值
    接下来就是存储元素进行查找判断。值得注意的是,此题不能一次性把整个数组全部赋值给散列表,因为数组中可能有重复元素,例如如下的测试用例:[0,4,3,0] 0;而散列表有个特点是当给同一个key赋值的时候,
    会按照最新的值为准,所以这个测试用例的键key=0时候,value将会变为3,这样就把索引为0的数组元素弄丢了。以下是本人犯的错误:

    public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i=0;i<nums.length;i++){
      map.put(nums[i],i);
    }
    for(int i=0;i<nums.length;i++){
      if(map.containsKey(target-nums[i])){
        res[0] = i;
        res[1] = map.get(target-nums[i]);
      }
    }
    return res;
    }

    而正确的做法是每次先判断散列表里面是否含有target-nums[i]的值,如果不包含,再把nums[i]放进hashmap里面,以下是正确的解法:

    public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    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;
    }

  • 相关阅读:
    高精度A+B
    基本定积分求面积
    二进制算子集和
    linux命令
    Dubbo
    java 集合区别
    Java中Comparable和Comparator区别
    synchronized实现原理
    ThreadLocal 原理
    java volatile关键字
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6353625.html
Copyright © 2011-2022 走看看