leetcode 136 Single Number bit Option
程序员文章站
2023-11-04 12:09:52
Linked Url:https://leetcode.com/problems/single-number/ Given a non-empty array of integers, every element appears twice except for one. Find that sin ......
linked url:
given a non-empty array of integers, every element appears twice except for one. find that single one.
note:
your algorithm should have a linear runtime complexity. could you implement it without using extra memory?
example 1:
input: [2,2,1] output: 1
example 2:
input: [4,1,2,1,2] output: 4
solution:
the method is xor option, principles is : 0 xor 0 = 0; 0 xor 1 = 1;any num xor itself = 0,so we pass the array and xor its elements all,so the result which is we want.
ac code follow:
1 class solution { 2 public: 3 int singlenumber(vector<int>& nums) { 4 int res = nums[0]; 5 for(int i = 1;i < nums.size();++i) 6 res = nums[i]^res; 7 return res; 8 } 9 };
上一篇: python爬取盘搜的有效链接