刷题复习(二)数组-双指针

发布时间 2023-12-05 15:36:30作者: kopoo

刷题复习(二)数组-双指针

https://labuladong.gitee.io/algo/di-ling-zh-bfe1b/shuang-zhi-fa4bd/

1、删除有序数组中的重复项

慢指针用于统计不重复项,快指针用于不停前进对比是否有新的不重复项,有的话进行替换

class Solution {
    public int removeDuplicates(int[] nums) {
        int i = 0, j = i + 1;
        while (i <= nums.length - 1 && j <= nums.length - 1) {
            if (nums[i] != nums[j]) {
                i++;
                nums[i] = nums[j];
            }
            j++;
        }
        return i + 1;
    }
}

2、删除排序链表中的重复元素

和上面的数组比较类似


/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return head;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null) {
            if (fast.val != slow.val) {
                slow.next =fast;
                slow =slow.next;
            }
            fast = fast.next;
        }
        slow.next = null;
        return head;
    }
}
//leetcode submit region end(Prohibit modification and deletion)