[Link to this article]
Http://www.cnblogs.com/hellogiser/p/find-number-which-appears-1-time-while-the-remaining-numbers-appear-3-times.html
【Question]
In array A, except for A certain number x, all other numbers appear three times, and x appears once. Please provide the fastest way to find x.
【Analysis]
Calculate the number of times each number appears 1 in 32 bits, and then add the number of BITs corresponding to all the numbers. The resulting number is equal to 3, the three digits are offset in the process of getting the remainder of the three, and the remaining number is the number of times that each of the x has 1.
[Code]
C ++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
|
// 60_FineNumberAppearOnceTheOthersAppear3Times.cpp: Defines the entry point for the console application. // /* Version: 1.0 Author: hellogiser Blog: http://www.cnblogs.com/hellogiser Date: 2014/5/28 */ # Include "stdafx. h"
/* 1, 1, 2, 2, 3 001,001,001, 010,010,010 011 Number of 1: 003 + 030 + 011 = 044 044% 3 = 011 ==> 3 */ Int FindNumberAppearOnce_WithTheOther3Times (int data [], int length) { If (NULL = data | length <= 0) Return-1; Const int N = 32; // Count the 1 s of 32 bit Int counts [N] = {0 }; For (int I = 0; I <length; ++ I) { For (int j = 0; j <N; ++ j) { Counts [j] = (counts [j] + (data [I]> j & 1) % 3; } }
// Get the result Int result = 0; For (int j = 0; j <N; ++ j) Result + = (counts [j] <j ); Return result; }
Void test_base (int data [], int length) { Int result = FindNumberAppearOnce_WithTheOther3Times (data, length ); Printf ("% d \ n", result ); }
Void test_case1 () { Int data [] = {1, 1, 1, 2, 2, 2, 3 }; Int length = sizeof (data)/sizeof (int ); Test_base (data, length ); }
Void test_case2 () { Int data [] = {1, 1, 1, 2, 2, 2, 3, 3, 4 }; Int length = sizeof (data)/sizeof (int ); Test_base (data, length ); }
Void test_main () { Test_case1 (); Test_case2 (); }
Int _ tmain (int argc, _ TCHAR * argv []) { Test_main (); Return 0; } /* 3 4 */ |
[Reference]
Http://blog.csdn.net/zhu_liangwei/article/details/11352999
Http://ouscn.diandian.com/post/2013-10-06/40052170552
Http://stackoverflow.com/questions/7338437/finding-an-element-in-an-array-that-isnt-repeated-a-multiple-of-three-times
Http://www.sysexpand.com /? Path = exercises/number-appearing-once-in-array-of-numbers-appearing-three-times
[Link to this article]
Http://www.cnblogs.com/hellogiser/p/find-number-which-appears-1-time-while-the-remaining-numbers-appear-3-times.html