文章目錄
- 雙指針
-
- Easy
-
- 283.[零移動](https://leetcode-cn.com/problems/move-zeroes/submissions/)
-
- 題目描述
- 思路
- 實作方法
- 代碼
- 26.[删除排序數組中的重複項](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/)
- 141.[ (判斷)環形連結清單](https://leetcode-cn.com/problems/linked-list-cycle/)
-
- 思路
- 代碼
雙指針
Easy
283.零移動
題目描述
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcsQXYtJ3bm9CXldWYtlWPzNXZj9mcw1ycz9WL49jb1c0Y1VlMahWMXFGdBR1T1U1RNRTU6llMNJTWy0UbNBTQEpVMnpmT0UFRalXTU5UaWpWT100VPJTUH1Uba1WWtpleNl3aU1EMFRUT31kaOlXUX9EbapmT4lkeNhmRU1kaapHT0ljMZVHNykFdVdkW250RkxmVHJWdNdVY3lTeMZTTINGMShUYvwlbj5yZtlmbkN3YuQnclZnbvN2Ztl2Lc9CX6MHc0RHaiojIsJye.jpg)
思路
周遊數組,将數組中的非零元素全部前移,如:[1,0,2,0,3,0,4,0]變為[1,2,3,4,x,x,x,x],最後将數組的後
count
位用0填充。
實作方法
雙指針:
i
用于循環周遊數組,
lastNumberNotZero
表示數組中已填充的最後一位。
零元素計數器:
count
。
若
a[i] == 0
則
count++
。否則則将該非零元素移動至
nums[++lastNumberNotZero]
。
代碼
class Solution {
public void moveZeroes(int[] nums) {
int lastNumberNotZero = -1;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0){
nums[++lastNumberNotZero] = nums[i];
}else {
count++;
}
}
for(int i = nums.length-count; i < nums.length; i++){
nums[i] = 0;
}
}
}
26.删除排序數組中的重複項
141. (判斷)環形連結清單
思路
- 使用兩個指針
和fast
slow
- 每次循環前判斷
和fast.next
是否等于fast.next.next
null
- 若等于有其一等于
則表示,連結清單不循環null
- 若等于有其一等于
- 若連結清單成環,則
與fast
必回相遇slow
代碼
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null){
return false;
}
ListNode fast = head, slow = head;
do{
if (fast.next == null || fast.next.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}while (slow != fast);
return true;
}
}