C#LeetCode刷题之#136-只出现一次的数字(Single Number)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4046 访问。

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

输入: [2,2,1]

输出: 1

输入: [4,1,2,1,2]

输出: 4


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?

Input: [2,2,1]

Output: 1

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

Output: 4


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4046 访问。

public class Program {

    public static void Main(string[] args) {
        int[] nums = null;

        nums = new int[] { 4, 1, 2, 1, 2 };
        var res = SingleNumber(nums);
        Console.WriteLine(res);

        nums = new int[] { 2, 2, 1 };
        res = SingleNumber2(nums);
        Console.WriteLine(res);

        nums = new int[] { 5, 9, 3, 9, 3, 2, 5 };
        res = SingleNumber3(nums);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int SingleNumber(int[] nums) {
        var dic = new Dictionary<int, int>();
        for(var i = 0; i < nums.Length; i++) {
            if(dic.ContainsKey(nums[i])) {
                dic[nums[i]]++;
            } else {
                dic[nums[i]] = 0;
            }
        }
        foreach(var item in dic) {
            if(item.Value == 0) {
                return item.Key;
            }
        }
        return 0;
    }

    private static int SingleNumber2(int[] nums) {
        var table = new Hashtable();
        for(var i = 0; i < nums.Length; i++) {
            if(table.ContainsKey(nums[i])) {
                table.Remove(nums[i]);
            } else {
                table.Add(nums[i], nums[i]);
            }
        }
        var enumerator = table.Values.GetEnumerator();
        enumerator.MoveNext();
        return (int)enumerator.Current;
    }

    private static int SingleNumber3(int[] nums) {
        var result = 0;
        foreach(var num in nums) {
            result ^= num;
        }
        return result;
    }

}

以上给出3种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4046 访问。

4
1
2

分析:

显而易见,以上3种算法的时间复杂度均为: O(n) 。SingleNumber3的执行效率是最高的,并且没有使用额外的空间,意思是指算法的空间复杂度为 O(1) 。

SingleNumber3的解法分析参考我的另一篇博文 C#LeetCode刷题之#268-缺失数字(Missing Number)。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值