当前位置:网站首页>LeetCode 1089. 复写零
LeetCode 1089. 复写零
2022-07-03 08:49:00 【Sasakihaise_】
【队列】没想出太好的方法来,所以只能先把数暂存到队列中模拟了
1.如果当前数字非0,直接进队列
2.如果当前数字为0,把两个0进队列
3.修改当前位置为队列的头
class Solution {
public void duplicateZeros(int[] arr) {
Queue<Integer> queue = new LinkedList();
for(var i = 0; i < arr.length; i++){
if(arr[i] != 0) queue.offer(arr[i]);
else {
queue.offer(0); queue.offer(0);
}
arr[i] = queue.poll();
}
}
}【双指针】其实可以不用队列,我们可以通过双指针来看走原数组的大小真正需要的数字个数,然后从后向前修改数组。
举个:1,0,2,3,0,4,5,0
设置双指针i,j一开时都指向0,j为较快的那个指针
1.i = j = 0,nums[i] != 0,i和j都往后走一个
2.i = j = 1, nums[i] == 0, i向后走1,j向后走2
直到j走到n-1,此时i的位置就是修改后数组能达到的数字值的极限了。
【细节】0,1,0,0 这种情况,应该是0,0,1,0,但是我们发现i指针走到了第三个0的位置,而j已经超过了4,所以这种特殊情况要额外判断一下。
class Solution {
// 双指针 9:44 10
public void duplicateZeros(int[] arr) {
int i = 0, j = 0, flag = 0;
while(j < arr.length){
if(arr[i] == 0){
j++;
if(j == arr.length) flag = 1;
else j++;
}
else j++;
i++;
}
i--;
for(j = arr.length - 1; j >= 0;){
if(arr[i] == 0){
if(flag == 1){
arr[j--] = 0; flag = 0;
}else{
arr[j--] = 0; arr[j--] = 0;
}
}else{
arr[j--] = arr[i];
}
i--;
}
}
}
边栏推荐
- 状态压缩DP AcWing 291. 蒙德里安的梦想
- LeetCode 241. 为运算表达式设计优先级
- How to use Jupiter notebook
- Markdown learning
- First Servlet
- [concurrent programming] concurrent tool class of thread
- 我們有個共同的名字,XX工
- Mortgage Calculator
- Unity multi open script
- PHP mnemonic code full text 400 words to extract the first letter of each Chinese character
猜你喜欢

Gif remove blank frame frame number adjustment

How to use Jupiter notebook

记忆化搜索 AcWing 901. 滑雪
![[concurrent programming] consistency hash](/img/5e/3d0a52caa8ca489a6e6267274bbb39.jpg)
[concurrent programming] consistency hash
![[redis] redis persistent RDB vs AOF (source code)](/img/57/b6a86c49cedee31fc00dc5d1372023.jpg)
[redis] redis persistent RDB vs AOF (source code)

LeetCode 535. TinyURL 的加密与解密

Format - C language project sub file

剑指 Offer II 091. 粉刷房子

Dom4j traverses and updates XML

状态压缩DP AcWing 91. 最短Hamilton路径
随机推荐
[rust notes] 07 structure
Sending and receiving of request parameters
MySQL three logs
【Rust 笔记】13-迭代器(上)
SQL statement error of common bug caused by Excel cell content that is not paid attention to for a long time
Apache startup failed phpstudy Apache startup failed
22-06-28 西安 redis(02) 持久化机制、入门使用、事务控制、主从复制机制
Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
[concurrent programming] collaboration between threads
Drawing maze EasyX library with recursive backtracking method
DOM 渲染系统(render mount patch)响应式系统
LeetCode 324. 摆动排序 II
Mortgage Calculator
cres
Query XML documents with XPath
MySQL index types B-tree and hash
The difference between if -n and -z in shell
[concurrent programming] consistency hash
[rust notes] 12 closure
22-06-27 西安 redis(01) 安装redis、redis5种常见数据类型的命令