iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
0
自我挑戰組

刷題記錄與人生分享系列 第 27

DAY27 Single Number

題目:

https://leetcode.com/problems/single-number/
找出唯一出現過一次的數字。(面試中偶爾會看到測試你能不能將XOR的特性融入到程式中)

解題思路:

利用XOR的特性,相同數字進行XOR會變為0所以不同的數字進行XOR,最終結果將會變成唯一的那個數字。

C版本:

int singleNumber(int* nums, int numsSize) {
    int count = 0;
    for(int i = 0;i<numsSize;i++)
        count = count^nums[i];
    return count;
}

Javascript版本:

var singleNumber = function(nums) {
    var result = 0;
    for(var i = 0; i<nums.length; i++)
    {
        result = result ^ nums[i];
    }
    return result;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

You must believe in yourself first, and others will believe in you.
你要先相信自己,別人才願意相信你。


上一篇
DAY26 Remove Linked List Elements
下一篇
DAY28 Invert Binary Tree
系列文
刷題記錄與人生分享34
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言