码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 136. 只出现一次的数字

时间:2020-05-17 09:14:57      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:div   nlog   tco   数字   空间   技术   i++   img   enum   

首先想到的是异或,会出现一个与不为零得值

可以使用暴力查找或者快排,快排复杂度是o(nlogn)

或者是使用hash表,但是会占用多余得空间复杂度

异或:

class Solution {
    public int singleNumber(int[] nums) {
        int ans=nums[0];
        if(nums.length>1){
            for(int i=1;i<nums.length;i++){
                ans=ans^nums[i];
            }
        }
        return ans;
    }
}

技术图片

 

 hash表:

class Solution {
    public int singleNumber(int[] nums) {
       Map<Integer,Integer> map=new HashMap<>();
        for(Integer i:nums){
            Integer count=map.get(i);
            count=count==null?1:++count;
            map.put(i,count);
        }

        for(Integer i:map.keySet()){
            Integer count=map.get(i);
            if(count==1){
                return i;
            }
        }
        return -1;
    }
}

技术图片

 

[LeetCode] 136. 只出现一次的数字

标签:div   nlog   tco   数字   空间   技术   i++   img   enum   

原文地址:https://www.cnblogs.com/doyi111/p/12903175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!