[Leetcode] Single Number
Given an array of integers, every element appears twice should t for one. Find that single one.
There have been a lot of things in the past two months. I have no time to study, do questions, or write blogs when my thesis is started or my family changes. Now, I feel that I have not done many things in place, so I have to turn over all the questions I have done before to help me understand new things ~
Now, I recall that this is the first leetcode question that I did when I first came into contact with algorithms. At that time, I got a question, and I felt deeply impressed by leetcode. After a long time, I felt that using the hash table in the data structure I learned in the second year of my undergraduate course could solve this problem. However, the level of c ++ is too low, and I knew nothing about the alien species such as the Associated container, so it has never been implemented. Then I began to search for the answer on the Internet, and the answer was backward to the bitwise operation-an exception or a solution to this problem. I once again felt that my IQ was crushed.
Any number is different from itself or has to be zero. When I see this sentence, I feel so cool. (the scenario where I can make up for the coders to comfort myself is empty afterwards, and I cannot have any children ). Any difference between the number and zero or it has to be itself. This... the diaosi is ultimately a diaosi TT.
Let's get down to the truth. below is the code for this idea.
class Solution{public:int singleNumber(int A[], int n) {int answer = A[0];for(int i = 1;i < n; i++){answer = answer ^ A[i];}return answer;}};
Besides the hash table concept, we later used the associated container map for implementation. We tested it ourselves, but the OJ system reported that the storage space overflows. I tried it again in the same way. Although the space complexity of this method is O (n), I always think this method is more practical or common, changing the repeat times of array elements is still used (but bit operations are not supported). It can also solve Single Number II. The following code is used:
class Solution{public:int singleNumber(int A[], int n) {map
m;for (int i = 0; i < n; i++){if (m.count(A[i])){m[A[i]]++;}else{m[A[i]] = 1;}}for (map
::iterator it = m.begin(); it != m.end(); it++){if (it->second == 1) return it->first;}return 0;}};