classSolution(object): defcontainsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ tank=set() for num in nums: if num in tank: returnTrue tank.add(num) returnFalse
Exercise 2:Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
binary:二进制;XOR: exclusive OR
result^=nums —- result=result^nums
nums^nums=0
nums^0=nums
x^y^z =(x^z)^y
XOR is under the binary calculation
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<vector> usingnamespace std;
classSolution { public: intsingleNumber(vector<int>& nums){ int result=0; for (int key : nums){ result^=key; } return result; } };
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defsingleNumber(self, nums): """ :type nums: List[int] :rtype: int """ # 使用位运算 XOR 来解决问题 result = 0 for num in nums: result ^= num # XOR 操作 return result
Exercise 3: Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
classSolution(object): defintersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ num1=set(nums1) num2=set(nums2) # Method 1: # for nu1 in num1: # if nu1 in num2: # result.append(nu1) # return result
# Method 2: result= list(num1&num2) return result ```
> *unordered_set<int>* set1 is the way to create the setin C++ - list1.push_back(key) is to add elements inlist - set1.insert(key) is to add elements inset - set1.erase(key) is to delet elements inset/list