leetcode 136. Single Number
程序员文章站
2022-04-09 17:09:19
题意给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。Example 1:Input: nums = [2,2,1]Output: 1Example 2:Input: nums = [4,1,2,1,2]Output: 4Example 3:Input: nums = [1]Output: 1解a ^ b ^ b = a根据异或运算的性质可知,把所有元素参与异或运算,即得到答案。// Runtime: 1 ms, fast...
题意
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
解
a ^ b ^ b = a
根据异或运算的性质可知,把所有元素参与异或运算,即得到答案。
// Runtime: 1 ms, faster than 74.06% of Java online submissions for Single Number.
//Memory Usage: 39.3 MB, less than 6.29% of Java online submissions for Single Number.
public int singleNumber(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int rst = nums[0];
for (int i = 1; i < nums.length; i++)
rst ^= nums[i];
return rst;
}
本文地址:https://blog.csdn.net/he25819/article/details/109244139
推荐阅读
-
leetcode 136 Single Number bit Option
-
[leetcode] 306. Additive Number 解题报告
-
LeetCode_#9_回文数 Palindrome Number_C++题解
-
【LeetCode】806. Number of Lines To Write String
-
Leetcode 1498. Number of Subsequences That Satisfy the Given Sum Condition (python)
-
LeetCode 1020. Number of Enclaves 解题报告(python)
-
Leetcode 1530. Number of Good Leaf Nodes Pairs (python)
-
Leetcode 200. Number of Islands (python+cpp)
-
LeetCode 1254. Number of Closed Islands解题报告(python)
-
【LeetCode】762. Prime Number of Set Bits in Binary Representation