首页 > 其他 > 详细

Letcode做题记录------真都是神仙

时间:2019-12-19 14:52:03      阅读:81      评论:0      收藏:0      [点我收藏+]

两个数相加寻找目标数

通过建立补值与序号的Hash表,遍历数组中的元素判断是否存在Hash表中的补值,找到前面与其值互补的序号。

这哥们的代码效率超过类99.06%的人。

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indexs = new int[2];
        
        // 建立k-v ,一一对应的哈希表
        HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length; i++){
            if(hash.containsKey(nums[i])){
                indexs[0] = i;
                indexs[1] = hash.get(nums[i]);
                return indexs;
            }
            // 将数据存入 key为补数 ,value为下标
            hash.put(target-nums[i],i);
            //建立补数与序号的键值,如果数组中的书和hash表中的补数相同,那么就可以找到             
       //对应的序号,与当前序号组成目标数。 } // // 双重循环 循环极限为(n^2-n)/2 // for(int i = 0; i < nums.length; i++){ // for(int j = nums.length - 1; j > i; j --){ // if(nums[i]+nums[j] == target){ // indexs[0] = i; // indexs[1] = j; // return indexs; // } // } // } return indexs; } }

Letcode做题记录------真都是神仙

原文:https://www.cnblogs.com/Keygun/p/12067233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!