Leet Code OJ 136. Single Number [Difficulty: Medium]
题目:
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?
分析:
题意是给定一个数组,该数组除了一个元素只出现一次外,其他元素均出现2次,找出这个出现一次的元素。Note中要求具有线性复杂度,也就是O(n)。
本题的考察点是异或运算,解题的关键是利用异或运算的交换律:a ⊕b ⊕ c = a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c,以及a ⊕ a = 0。对数组的全部元素进行异或运算,将里面出现2次的元素交换到一起,这样由于a ⊕ a = 0,最终结果就是那个只出现一次的元素。
代码实现1(时间复杂度O(n)):
public class Solution {public int singleNumber(int[] nums) {int res=0;for(int i=0;i<nums.length;i++){res=res^nums[i];}return res;}
}
代码实现2(时间复杂度O(n^2)):
public class Solution {public int singleNumber(int[] nums) {int target;for(int i=0;i<nums.length;i++){target=nums[i];boolean found=false;for(int j=0;j<nums.length;j++){if(target==nums[j]&&i!=j){found=true;break;}}if(found==false){return target;}}return 0;}
}
Leet Code OJ 136. Single Number [Difficulty: Medium]相关推荐
- Leet Code OJ 268. Missing Number [Difficulty: Medium]
题目: Given an array containing n distinct numbers taken from 0, 1, 2, -, n, find the one that is miss ...
- Leet Code OJ 260. Single Number III [Difficulty: Medium]
题目: Given an array of numbers nums, in which exactly two elements appear only once and all the other ...
- Leet Code OJ 338. Counting Bits [Difficulty: Medium]
题目: Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate ...
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
题目: Write an algorithm to determine if a number is "happy". A happy number is a number def ...
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
题目: Write a program to check whether a given number is an ugly number. Ugly numbers are positive num ...
- Leet Code OJ 91. Decode Ways [Difficulty: Medium]
题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: ' ...
- Leet Code OJ 66. Plus One [Difficulty: Easy]
题目: Given a non-negative number represented as an array of digits, plus one to the number. The digit ...
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
题目: Given an array nums, write a function to move all 0's to the end of it while maintaining the rel ...
最新文章
- java使用Cookie判断用户登录情况
- 【Java】全站编码过滤器GenericEncodingFilter代码与配置
- 网络怎么排错?手把手教你
- Cpp / 拷贝构造函数的参数为什么必须使用引用类型
- (上)挖掘传统行业日志大数据的无限价值
- 计算机操作系统(8):进程的控制
- 框架源码专题:springIOC的加载过程,bean的生命周期,结合spring源码分析
- python中join和split使用
- BI与大数据之间的差距有哪些
- 如何简化卷积神经网络_卷积神经网络:简化
- PAT L1 049 天梯赛座位分配
- 闭环控制 matlab仿真,反馈闭环控制系统Simulink仿真(带电流补偿的电压内环,直流调速)...
- levene ttest
- python实现骰子猜大小游戏
- unity 粒子插件_unity的基本认识——走进unity
- 是堆内存分为年轻代和年老代!!!
- ITE平台开发 chapter 3-database使用
- CE游戏修改器制作详解
- 记录maskrcnn训练:训练集制备、tensorflow+keras包安装、gpu运行推荐组合、soft-nms使用
- WORKNC 2020.0 win10系统启动错误0xc0000022