码迷,mamicode.com
首页 > 其他好文 > 详细

260. Single Number III

时间:2016-04-21 13:18:24      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

  问题: 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].

  解决:新技能get!  位运算的巧妙使用,特性:任何数字异或自身都为0

  代码:

  

 1 package com.wang.test;
 2  
 3 import javax.naming.ldap.SortControl;
 4 
 5 /*
 6  * @tittle:260. Single Number III
 7  * @author:wwwglin
 8  * @time:2016/04/18
 9  */
10 public class SingleNumberIII {
11     //任何数字异或自身都为0
12     public int[] singleNumber(int[] nums) {
13         int resTwo = 0;
14         int[] res = new int[2];
15         for (int i = 0; i < nums.length; i++) {
16             resTwo ^= nums[i];
17         }
18         // find the rigthest bit which is not 0
19         resTwo &= -resTwo;
20         for (int i = 0; i < nums.length; i++) {
21             if ((nums[i] & resTwo) == 0) {
22                 res[0] ^= nums[i];
23             } else {
24                 res[1] ^= nums[i];
25             }
26         }
27         return res;
28     }
29 
30     public static void main(String[] args) {
31         int[] nums = { 1, 2, 3, 5, 7, 2, 4, 1, 7, 5 };
32         int[] res = new SingleNumberIII().singleNumber(nums);
33         for (int i : res) {
34             System.out.println(i);
35         }
36         
37     }
38 }

 

260. Single Number III

标签:

原文地址:http://www.cnblogs.com/wwwglin/p/5416251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!