Single Number II

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

题目:有一个整形数组,数组中只存在一个整数只出现一次,其他的整数的个数都出现三次,找出只出现一次的数

public class LeetCode1 {
//    Given an array of integers, every element appears three times except for one. Find that single one.
//    给定一个整数数组,每个数都出现三次,只有一个数出现一次,找出只出现一次的那个数
//    Note:
//    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
//    你的算法应该有一个线性运行时的复杂性。你能实现它不使用额外的内存吗?

    public static  int singleNumber(int[] nums) {
        int length = nums.length;
        TreeMap<Integer,Integer> map = new TreeMap<Integer, Integer>();
        for(int i = 0 ;i < length;i++){
            if(null == map.get(nums[i])){
                map.put(nums[i], 1);
                continue;
            }

            if(map.get(nums[i]) == 1){
                map.put(nums[i],2);
                continue;
            }

            if(map.get(nums[i]) == 2){
                map.remove(nums[i]);
            }
        }

        int num = map.firstKey();

        return num;
    }

    public static void main(String[] args){
        //int[] nums = {3,3,1,3,5,5,6,6,5,7,7,7,6};
        int[] nums = {2,2,3,2};
        int num = singleNumber(nums);
        System.out.println(num);


    }
}

我又一次选择了用treemap来进行操作
之前有一题是一个整型数组中的数据,只有一个数字出现一次,其他的数字都出现两次,找出只出现一次的数字。我也是采用的使用treemap的方式,两者用的时间差不多。后来发现在可以使用异或运算,两个相同的数进行异或的结果为0,如果三个相同的数进行异或,结果为这个数本身,那么在一个几乎都是两个相同的数组成的数组中找出,只出现一次的数,则可以使用对所有的数进行异或的操作,这样得到的结果即为只出现一次的数。

int x = 123;
int y = x^x;
此时y的值为0int y = x^x^x;
此时y的值为x;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值