0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点# leetcode-136 只出现一次的数字

本题可以用 异或运算,规则是同0 ,最后剩下的数字就是只出现一次的数字


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

<p><strong>说明:</strong></p>

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

<p><strong>示例 1:</strong></p>

<pre><strong>输入:</strong> [2,2,1]
<strong>输出:</strong> 1
</pre>

<p><strong>示例 2:</strong></p>

<pre><strong>输入:</strong> [4,1,2,1,2]
<strong>输出:</strong> 4</pre>
<div><div>Related Topics</div><div><li>位运算</li><li>数组</li></div></div><br><div><li>👍 2630</li><li>👎 0</li></div>
*/

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int singleNumber(int[] nums) {
if(nums.length == 0 ){
return 0;
}

int res = nums[0];
for (int i = 1; i < nums.length; i++) {
res = res^nums[i];
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)

举报

相关推荐

0 条评论