关关的刷题日记32 – Leetcode 136. Single Number
Given an 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?
题目的意思是有一个数组,每个元素出现两次,只有一个元素出现了一次,让找出该元素。
思路:没细看题目,随手写了个map。
class Solution {public: int singleNumber(vector<int>& nums) { map<int,int>m; for(int x:nums) { m[x]++; } for(int x:nums) { if(m[x]==1) return x; } return 0; }};
方法2:发现题目要求O(n)时间复杂度,而且不需要额外空间。Map开辟了额外空间,不满足要求。采用异或的思路,遍历一边该数组即可。 aa=0 ab=ba a0=a
class Solution {public: int singleNumber(vector<int>& nums) { int re=0; for(int x:nums) { re^=x; } return re; }};
人生易老,唯有陪伴最长情,加油!
以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang,注明Leetcode刷题)。
本文分享自微信公众号 - 专知(Quan_Zhuanzhi),作者:关关
原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。
原始发表时间:2017-11-11
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句