The elements in an int array have this feature: 22 appears, only 2 numbers are separate.
Find these 2 numbers and return an array of int.
Given An array of numbers nums , in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the 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. The above example, is
[5, 3] also correct.
- Your algorithm should run in linear runtime complexity. Could implement it using only constant space complexity?
Implemented in Java, the core method is as follows:
Public Static int[] Singlenumber (int[] nums) { if(nums.length==2&&nums[0]!=nums[1]){ returnNums; } HashSet<Integer> store=NewHashset<integer>(); HashSet<Integer> result=NewHashset<integer>(); for(inti=0;i<nums.length;i++){ if(!Result.add (Nums[i])) {Result.remove (nums[i]); Store.add (Nums[i]); }Else{ if(Store.contains (Nums[i])) {Result.remove (nums[i]); } } } int[] print=New int[2]; print[0]=Result.iterator (). Next (); Result.remove (Result.iterator (). Next ()); print[1]=Result.iterator (). Next (); returnPrint; }
Using HashSet to store the data
The Add method of HashSet returns a Boolean value. Returns true when adding data for the first time, and returns False when the same data is added
New Hashset<integer>(); System.out.print (Test.add (1) + "\ T"); System.out.print (Test.add (1)); System.out.print ("\ n" + test.add (2) + "\ T"); System.out.println (Test.add (3)); for (int i = 1;i <= 3; i++) { System.out.print ("item" + i + ":" + test.iterator (). Next () + "\ T"
); Test.remove (Test.iterator (). Next ());
//
Delete current value }
Where the data "1" performed 2 additions;
True False
Truetrue
Item1:1item2:2item3:3
Can be seen added 2 times, actually only 1
Use the Boolean value returned by the Add method to determine if the data has been added to the map
Find the singular