zoukankan      html  css  js  c++  java
  • Two Sum

    Two Sum

    问题:

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

    思路:

      hashtable

    我的代码:

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
             HashMap<Integer,Integer> save = new HashMap<Integer,Integer>();
             HashMap<Integer,Integer> duplicate = new HashMap<Integer,Integer>();
             for(int i = 0; i < numbers.length; i++)
             {
                 if(save.containsKey(numbers[i]))
                 {
                     duplicate.put(numbers[i],i+1);
                 }
                 else
                 {
                     save.put(numbers[i],i+1);
                 }
             }
             int[] rst = new int[2];
             for(int i = 0; i < numbers.length; i++)
             {
                 int val = numbers[i];
                 int remain = target - val;
                 if(val == remain)
                 {
                     if(duplicate.containsKey(val))
                     {
                         rst[0] = i+1;
                         rst[1] = duplicate.get(val);
                         return rst;
                     }
                     continue;
                 }
                 if(save.containsKey(remain))
                 {
                     rst[0] = i+1;
                     rst[1] = save.get(remain);
                     return rst;
                 }
             }
             return rst;
        }
    }
    View Code

    他人代码:

    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>();
    
        for(int i = 0; i < numbers.length; i++){
            if(table.containsKey(numbers[i])){
                result[0] = table.get(numbers[i]) + 1;
                result[1] = i + 1;
            }
            table.put(target - numbers[i], i);
        }
    
        return result;
    }
    View Code

    学习之处:

    • 我的代码里面考虑了那么多的Corner Case又是用两个HashTable进行存储,又是判断是否是一个指啊。
    • 别人代码用的是回头望月,便往后走,边看看前面是否符合条件,一遍扫描就OK,一个Hashtable就OK,也没有那么多的Corner Case
    • 别人的代码简洁,大气,上档次---简洁之美
  • 相关阅读:
    实验四 决策树
    实验三 朴素贝叶斯算法及应用
    实验二 k邻近算法及应用
    实验一 感知器及其应用
    实验三 面向对象分析与设计
    个人作业三---ATM管理系统
    流程图与活动图的区别于联系
    个人作业---四则运算生成程序
    面向对象分析与设计
    结构化分析与设计
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4335125.html
Copyright © 2011-2022 走看看