美文网首页
Two sum 最佳解法

Two sum 最佳解法

作者: dearjj | 来源:发表于2019-08-20 16:18 被阅读0次
    轉自leetcode
    

    看了一下java的最優解,感嘆真的技不如人
    簡單來説就是把當前complement的數字在原來array的位數,存進新array原數字為index的位置上面,然後每次都去找complement

            int max= 2047;
            int temp;
            int[] test=new int[max+1];
            for(int i=0;i<nums.length;i++){
                temp=(target-nums[i])&max;// target為0時出現負數的情況
                if(test[temp]!=0){
                    return new int[]{test[temp]-1, i};
                }
                test[nums[i]&max] =i+1;
            }
            throw new IllegalStateException("no solution");
    

    時間是1ms

    相关文章

      网友评论

          本文标题:Two sum 最佳解法

          本文链接:https://www.haomeiwen.com/subject/fybpsctx.html