当前位置:网站首页>LeetCode面试题
LeetCode面试题
2022-08-05 05:19: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)) {
// 列表不包括 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) {
// 判断哈希表中是否已存在值
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) {
// 众数数量
int ans = nums.length / 2;
// 依次遍历统计每一个元素出现的次数
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];
}
}
边栏推荐
- [Paper Intensive Reading] The relationship between Precision-Recall and ROC curves
- To TrueNAS PVE through hard disk
- VLAN details and experiments
- D46_给刚体施加的力
- 小度 小度 在呢!
- 【Day1】(超详细步骤)构建软RAID磁盘阵列
- 不吹不黑,这的确是我看过微服务架构最好的文章!
- Getting Started Documentation 12 webserve + Hot Updates
- spark源码-任务提交流程之-1-sparkSubmit
- Getting Started Document 09 Standalone watch
猜你喜欢

Introductory document 05-2 use return instructions the current task has been completed

论那些给得出高薪的游戏公司底气到底在哪里?

VLAN details and experiments

Dsf5.0 bounced points determine not return a value

每日一题-最长回文子串-0714

The problem of calling ds18b20 through a single bus
![[Day1] (Super detailed steps) Build a soft RAID disk array](/img/40/cda8e5522c2795e03c0d47e8a689f8.png)
[Day1] (Super detailed steps) Build a soft RAID disk array

Autoware--北科天绘rfans激光雷达使用相机&激光雷达联合标定文件验证点云图像融合效果

Unity中的GetEnumerator 方法及MoveNext、Reset方法

添加新硬盘为什么扫描不上?如何解决?
随机推荐
网站ICP备案是什么呢?
腾讯内部技术:《轩辕传奇》服务器架构演变
入门文档04 一个任务依赖另外一个任务时,需要按顺序执行
spark算子-map vs mapPartitions算子
【Day8】 RAID磁盘阵列
每日一题-电话号码的字母组合-0717
Unity huatuo 革命性热更系列1.2 huatuo热更环境安装与示例项目
阿里云视频点播
Getting Started Documentation 10 Resource Mapping
VRRP原理及命令
入门文档05-2 使用return指示当前任务已完成
CIPU,对云计算产业有什么影响
[Day1] VMware software installation
To TrueNAS PVE through hard disk
【Day8】磁盘及磁盘的分区有关知识
spark算子-coalesce算子
静态路由
Getting Started Doc 08 Conditional Plugins
洞察互联网大趋势,读完这篇文章你就彻底了解中文域名
每日一题-最长回文子串-0714