当前位置:网站首页>LeetCode Interview Questions
LeetCode Interview Questions
2022-08-05 06:13:00 【CrazyQiQi】
LeetCode面试题
热身
1. 只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素.
说明:
你的算法应该具有线性时间复杂度. 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
解法1:列表操作
class Solution {
// 列表操作
public int singleNumber(int[] nums) {
List<Integer> list = new ArrayList<>(); // 创建新的列表
for(int num : nums) {
if(!list.contains(num)) {
// List does not include num
list.add(num);
} else {
list.remove((Object)num); // 移除重复 num
}
}
return list.get(0);
}
}
解法2:哈希表
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Object> map = new HashMap<>();
for(int num : nums) {
// Check if a value already exists in the hash table
if(!map.containsKey(num)) {
map.put(num, null);
} else {
map.remove(num);
}
}
// 查找对应的 key
return map.keySet().iterator().next();
}
}
解法3:位操作
概念
如果我们对 0 和二进制位做 XOR 运算,得到的仍然是这个二进制位
a ⊕ 0=a
如果我们对相同的二进制位做 XOR 运算,返回的结果是 0
a ⊕ a=0
XOR 满足交换律和结合律
a ⊕ b ⊕ a = (a ⊕ a) ⊕ b= 0 ⊕ b = b
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int num : nums) {
res ^= num;
}
return res;
}
}
2. 多数元素
多数元素
给定一个大小为 n 的数组,找到其中的多数元素.多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素.
你可以假设数组是非空的,并且给定的数组总是存在多数元素.
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
解法1:暴力解法
class Solution {
public int majorityElement(int[] nums) {
// Mode quantity
int ans = nums.length / 2;
// Iterate through and count the number of occurrences of each element in turn
for(int num : nums) {
int count = 0;
for(int a : nums) {
if(a == num) count++;
}
if (count > ans) {
return num;
}
}
}
}
解法2:排序算法
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
边栏推荐
猜你喜欢

2020,Laya最新中高级面试灵魂32问,你都知道吗?
时间复杂度和空间复杂度

One-arm routing and 30% switch
![[Day8] Commands involved in using LVM to expand](/img/ba/39b81cbcecec9bc54a710ff9dba81a.png)
[Day8] Commands involved in using LVM to expand

markdown编辑器模板

OpenCV3.0 兼容VS2010与VS2013的问题
![[Paper Intensive Reading] The relationship between Precision-Recall and ROC curves](/img/8f/3c9944db96eef623779a5abe68355b.png)
[Paper Intensive Reading] The relationship between Precision-Recall and ROC curves

lvm逻辑卷及磁盘配额

Getting Started Document 09 Standalone watch

NIO工作方式浅析
随机推荐
lvm逻辑卷及磁盘配额
D39_坐标转换
错误类型:reflection.ReflectionException: Could not set property ‘xxx‘ of ‘class ‘xxx‘ with value ‘xxx‘
入门文档03 区分开发与生产环境(生产环境才执行‘热更新’)
spark源码-任务提交流程之-4-container中启动executor
网站ICP备案是什么呢?
Getting Started Documentation 12 webserve + Hot Updates
Contextual non-local alignment of full-scale representations
Autoware中安装Yolo3目标检测模块遇到的问题
Wireshark抓包及常用过滤方法
入门文档10 资源映射
LeetCode面试题
Unity物理引擎中的碰撞、角色控制器、Cloth组件(布料)、关节 Joint
I/O性能与可靠性
入门文档12 webserve + 热更新
The problem of calling ds18b20 through a single bus
IP数据包格式(ICMP协议与ARP协议)
spark源码-任务提交流程之-3-ApplicationMaster
spark source code - task submission process - 5-CoarseGrainedExecutorBackend
Spark源码-任务提交流程之-6.1-sparkContext初始化-创建spark driver端执行环境SparkEnv