260. Single Number III, 260 single

Source: Internet
Author: User

260. Single Number III, 260 single

Given an array of numbersnums, 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:

Givennums = [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 shocould run in linear runtime complexity. cocould you implement it using only constant space complexity?

 

1/** 2 * Return an array of size * returnSize. 3 * Note: The returned array must be malloced, assume caller callfree (). 4 */5 int * singleNumber (int * nums, int numsSize, int * returnSize) {6 int flag = 0; 7 int I; 8 int k = 1; 9 int * res; 10 res = (int *) malloc (2 * sizeof (int )); // It Must Be malloc but not pass 11 res [0] = res [1] = 0; 12 for (I = 0; I <numsSize; I ++) // first exclusive or exclusive 2 numbers 13 flag ^ = nums [I]; 14 while (1) 15 {16 if (k & flag) // find the first digit in the binary system that is 1, then the number of the two digits is 1, and the other one is 017 break; 18 k = k <1; 19} 20 for (I = 0; I <numsSize; I ++) 21 {22 if (k & nums [I]) // class all the bitwise of 1, 23 res [0] ^ = nums [I]; // exclusive or outgoing 24 else with this value of 0 // likewise, the number of this digit 1 is 25 res [1] ^ = nums [I]; 26 27} 28 * returnSize = 2; 29 return res; 30}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.