[LeetCode] 136. Single Number

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

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

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

题目:给定一个非空整数数组,数组中有1个数只出现1次、其他数都出现2次,找出只出现1次的数。要求算法的时间复杂度是O(n)、空间复杂度是O(1)。

实现思路1(不满足时间复杂度要求):一种直观的做法是将数组排序,出现2次的数会出现在一起,因此两两检查,如果发现不相同的数或者最后只剩余一个数就找到了最终结果。这种算法的空间复杂度是O(1),但时间复杂度是O(nlogn)。

class Solution {
    public int singleNumber(int[] nums) {
        if (nums == null) throw new IllegalArgumentException("argument is null");
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i += 2)
            if (nums[i] != nums[i + 1])
                return nums[i];
        return nums[nums.length - 1];
    }
}

实现思路2(不满足空间复杂度要求):另一种直观的做法是用一个List保存数组中的数,如果当前遍历的数已经在List中则将这个数删除,否则就将这个数添加进List。由于数组中只有1个数出现1次且其他数都出现2次,因此这个List最终只会有1个数(最终结果)。这种算法的时间复杂度是O(n),但空间复杂度是O(n)。

class Solution {
    public int singleNumber(int[] nums) {
        if (nums == null) throw new IllegalArgumentException("argument is null");
        List<Integer> list = new ArrayList<>();
        for (int i : nums) {
            if (list.contains(i))
                list.remove(new Integer(i));
            else
                list.add(i);
        }
        return list.get(0);
    }
}

实现思路3(满足题目要求):利用异或运算的特性,即a^b^a=b。由于数组中只有1个数出现1次,其余数都出现2次,因此令所有数做异或运算的结果就是题目要求的最终结果。

class Solution {
    public int singleNumber(int[] nums) {
        if (nums == null) throw new IllegalArgumentException("argument is null");
        int result = nums[0];
        for (int i = 1; i < nums.length; i++)
            result = result ^ nums[i];
        return result;
    }
}

参考资料:

https://leetcode.com/problems/single-number/solution/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值