def test_single_number(self): random.seed('test') self.assertEqual(0, single_number([1, 0, 2, 1, 2, 3, 3])) self.assertEqual(101, single_number([101])) single = random.randint(1, 100000) nums = [random.randint(1, 100000) for _ in range(1000)] nums *= 2 # nums contains pairs of random integers nums.append(single) random.shuffle(nums) self.assertEqual(single, single_number(nums))
def test_single_number(self): random.seed('test') self.assertEqual(0, single_number([1, 0, 2, 1, 2, 3, 3])) self.assertEqual(101, single_number([101])) single = random.randint(1, 100000) nums = [random.randint(1, 100000) for _ in range(1000)] nums *= 2 # nums contains pairs of random integers nums.append(single) random.shuffle(nums) self.assertEqual(single, single_number(nums))
""" 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. Limitation: Time Complexity: O(N) and Space Complexity O(1) 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. Solution: 1. Use XOR to cancel out the pairs and isolate A^B 2. It is guaranteed that at least 1 bit exists in A^B since A and B are different numbers. ex) 010 ^ 111 = 101 3. Single out one bit R (right most bit in this solution) to use it as a pivot 4. Divide all numbers into two groups. One group with a bit in the position R One group without a bit in the position R 5. Use the same strategy we used in step 1 to isolate A and B from each group. """ # Two element once from algorithms.bit import single_number,single_number2,single_number3 nums = [1, 2, 1, 3, 2, 5] print(single_number(nums)) ## XXX print(single_number2(nums)) ## XXX print(single_number3(nums))
""" Given an array of integers, every element appears twice except for one. Find that single one. NOTE: This also works for finding a number occurring odd number of times, where all the other numbers appear even number of times. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ ## one once from algorithms.bit import single_number a=[4,1,2,1,2] b=[2,2,1] print(single_number(a)) print(single_number(b))