[LeetCode] 136--Single Number --Medium--

今天又来做题了,因为Find the Duplicate Number一直没想出来,但又不想直接上网看答案,只好做与它类似的题目。
Single Number

Given an 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?

Hide Tags Hash Table Bit Manipulation
Hide Similar Problems (M) Single Number II (M) Single Number III (M) Missing Number (H) Find the Duplicate Number

原题链接:https://leetcode.com/problems/single-number/

大概意思是:给出一个整型数组,找出没有重复的那一个数字。
要求,1时间效率是线性的;2能否实现不利用额外存储空间?

解法一:虽然说要求时间效率是线性,但是想试一下先排序后查找的方法,时间效率O(nlogn)。
*这里需要注意的是排序后的最后一个数字。

public class Solution {
    public int singleNumber(int[] nums) {

        if (nums == null) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 1; i++) {
            if (0 == i % 2 && nums[i] != nums[i + 1]) {
                return nums[i];
            }
        }
        return nums[nums.length - 1];
    }
}

解法二:利用map,时间效率接近O(n)。

public class Solution {
    public int singleNumber(int[] nums) {
        if (nums == null) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        HashMap<Integer, Integer> numMap = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int sizeBefore = numMap.size();
            numMap.put(nums[i], nums[i]);
            int sizeAfter = numMap.size();
            if (sizeBefore == sizeAfter) {
                numMap.remove(nums[i]);
            }
        }
        return (int) numMap.entrySet().iterator().next().getValue();
    }
}

解法二:利用异或操作,时间效率O(n)。这个真的想不出来。
解法的原链接:https://leetcode.com/discuss/6170/my-o-n-solution-using-xor?show=28023#c28023
原理是异或操作满足交换律:
array is {2,1,4,5,2,4,1} then it will be like we are performing this operation,
((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5.

int singleNumber(int A[], int n) {
    int result = 0;
    for (int i = 0; i<n; i++)
    {
        result ^=A[i];
    }
    return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值