码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode136]Single Number

时间:2015-12-18 22:49:06      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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?

中文(给定一个整数的数组,每个整数都出现了两次,只有一个出现了一次,找到它  建议不使用额外的内存空间)

思路:利用^运算符  

二元 ^ 运算符是为整型和 bool 类型预定义的。对于整型,^ 将计算操作数的按位“异或”。对于 bool 操作数,^ 将计算操作数的逻辑“异或”;也就是说,当且仅当只有一个操作数为 true 时,结果才为 true。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeetCode
{
    class SingleNumberSolution
    {
        //static void Main()
        //{
        //    SingleNumberSolution s = new SingleNumberSolution();
        //    int[] nums = {1, 1, 2, 3, 3, 4, 4};
        //    Console.WriteLine(s.SingleNumber(nums));
        //}

        public int SingleNumber(int[] nums)
        {
            int singleNum = nums[0];
            for (int i = 1; i < nums.Length; i++)
            {
                singleNum ^= nums[i];
            }
            return singleNum;
        }
    }
}

 

[LeetCode136]Single Number

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/5058315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!