只出现一次的数

给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。你可以按 任意顺序 返回答案。

进阶:你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?

示例 1:

输入:nums = [1,2,1,3,2,5]
输出:[3,5]
解释:[5, 3] 也是有效的答案。
示例 2:

输入:nums = [-1,0]
输出:[-1,0]
示例 3:

输入:nums = [0,1]
输出:[1,0]
提示:

2 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
除两个只出现一次的整数外,nums 中的其他数字都出现两次

解一:时间复杂度超出

class Solution {
    public int[] singleNumber(int[] nums) {
        int count = 0;
        int[] arr = new int[2];
        // ArrayList<Integer> ids = new ArrayList<>();
        int k =0;
        for(int i = 0;i<nums.length;i++){
            for(int j = 0 ;j<nums.length;j++){
                if(nums[i]==nums[j]){
                    count++;
                }

            }
            if(count==1){
                arr[k++] = nums[i];
            }
            count = 0;
        }
        return arr ;

    }
    
}

解二:位运算

class Solution {
    public int[] singleNumber(int[] nums) {
        int norx = 0;
        int x[] = {0,0};
        for(int num:nums){
            norx^=num;
        }
        int lbs = norx & (-norx);
        for(int num:nums){
            if((num&lbs)==0){
            x[0] ^=num;
            }
            else
            x[1] ^=num;

        }
        return x;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值