哈希oj---- >只出现一次的数字

题目要求:

分析:

要找出只出现一次的元素,用排序时间复杂度太高,暴力解法不适用,同样处理起来不好处理,最简单的首先就是考虑用哈希表,最后,通过了解也知道,异或运算同样可以解决,并且时间复杂度也不高

解题思路:

  • Map解决
  1. 将数组中的元素以key值的形式保存到Map中
  2. 遍历数组时,判断value值是否为1
  • Set解决
  1. 先将数组的第一个元素保存到Set中
  2. 遍历数组,如果有相同的不保存,并且删除Set里面相同的元素
  3. 将Set转换为数组并返回
  • 异或运算解决
  1. 根绝异或运算的特性,在二进制运算当中,相同为0,不同为1;

解题代码:

1.Map解决

class Solution {
    public int singleNumber(int[] nums) {
        Map<Integer,Integer> m = new HashMap<>();

        for(int i = 0;i < nums.length;i++){
            m.put(nums[i],m.getOrDefault(nums[i],0) + 1);
        }

        int[] array = new int[1];
        for(int i = 0;i < nums.length;i++){
            if(m.get(nums[i]) == 1){
                array[0] = nums[i];
                break;
            }
        }

        return array[0];
    }
}

2.Set解决

class Solution {
    public int singleNumber(int[] nums) {
        Set<Integer> s = new HashSet<>();
        s.add(nums[0]);
        for(int i = 1; i < nums.length;i++){
            if(s.contains(nums[i])){
                s.remove(nums[i]);
            }else{
                s.add(nums[i]);
            }
        }
        Integer[] array = s.toArray(new Integer[0]);

        return array[0];
    }
}

3.异或解决

class Solution {
    public int singleNumber(int[] nums) {
        //按位异或运算的结果有两种可能(二进制中)
        //1.相同异或为0
        //2.不同异或为1
        int ans = 0;
        for(int i = 0;i < nums.length;i++){
            ans ^= nums[i];
        }
        return ans;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值