algorithm & bitwise operation & the best leetcode solutions
algorithm & bitwise operation & the best leetcode solutions
leetcode 136 single-number
the better solution
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
return nums.reduce((sum, i) => sum ^ i, 0);
};
// Time complexity : O(n)
// Space complexity : O(1)
my solution
solution 1
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-08-015
* @modified
*
* @description 136 single-number
* @difficulty Easy
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
*/
const log = console.log;
var singleNumber = function(nums) {
let len = nums.length;
// obj unique key
const obj = {};
while(len) {
const value = nums[len - 1];
if(obj[value] === undefined) {
obj[value] = 1;
} else {
obj[value] += 1;
}
len--;
}
// log(`\nkeys`, Object.keys(obj))
// log(`values`, Object.values(obj))
// log(`entries`, Object.entries(obj))
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const item = obj[`${key}`];
if(item === 1) {
return key;
}
}
}
};
// Time complexity : O(n)
// Space complexity : O(n)
/*
输入: [2,2,1]
输出: 1
输入: [4,1,2,1,2]
输出: 4
*/
const test = [2,2,1];
const result = singleNumber(test);
log(`result =`, result)
// 1
const test2 = [4,1,2,1,2];
const result2 = singleNumber(test2);
log(`result2 =`, result2)
// 4
如何使用 js 计算两个数组的交集、差集、并集、补集
https://www.hangge.com/blog/cache/detail_1862.html
refs
https://leetcode-cn.com/problems/single-number/
https://leetcode.com/problems/single-number/
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13508826.html
未经授权禁止转载,违者必究!