失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 【leetcode79】Single Number III

【leetcode79】Single Number III

时间:2018-10-05 04:09:30

相关推荐

【leetcode79】Single Number III

题目描述:

给定一个数组,里面只有两个数组,只是出现一次,其余的数字都是出现两次,找出这个两个数字,数组形式输出

原文描述:

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

The order of the result is not important. So in the above example, [5, 3] is also correct.

Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

思路:

考虑使用位运算

-那数组分为两组,每个组只有一个出现一次的数字,单独进行异或处理,考虑用全部异或的方式

假设得到异或的结果是A,由于两个数字不同。A肯定有一个位是1,找到那个位,然后用来把这个数组分为两组

其中一个组的异或结果是B,输出【B,A ^ B】

代码:

public class Solution {public int[] singleNumber(int[] nums) {int xOne = 0;for (int x : nums) {xOne ^= x;}// 获取第一个位1的索引int k = 0;for (k = 0; k < Integer.SIZE; ++ k) {if (((xOne >>> k) & 1) == 1) {break;}}int xTwo = 0;for (int x : nums) {if (((x >>> k) & 1) == 1) {xTwo ^= x;}}return new int[] {xTwo, xOne ^ xTwo};}}

更多的leetcode的经典算法,查看我的leetcode专栏,链接如下:

leetcode专栏

我的微信二维码如下,欢迎交流讨论

欢迎关注《IT面试题汇总》微信订阅号。每天推送经典面试题和面试心得技巧,都是干货!

微信订阅号二维码如下:

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

如果觉得《【leetcode79】Single Number III》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。