天天看點

LeetCode——雙指針雙指針

文章目錄

  • 雙指針
    • 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.零移動

題目描述

LeetCode——雙指針雙指針

思路

周遊數組,将數組中的非零元素全部前移,如:[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;
    }
}