leetcode-26-删除排序数组中的重复项

问题:

解:

package com.example.demo;

public class Test26 {
    /**
     * 使用双指针方法,定义两个指针,head / last 头和尾,将last位置的值和head位置的值比较,如果同则head++,不同则将head位置
     * 的值赋值给++last之后的位置
     *
     * @param nums
     * @return
     */
    public int removeDuplicates(int[] nums) {
        int head = 1;
        int last = 0;
        while (head <= nums.length - 1) {
            if (nums[head] == nums[last]) {
                head++;
            } else {
                nums[++last] = nums[head];
                head++;
            }
        }
        return last + 1;
    }

    public static void main(String[] args) {
        Test26 t = new Test26();
        int[] arr = {1, 1, 2, 3, 4, 4, 5};
        int i = t.removeDuplicates(arr);
        System.out.println(i);
    }
}
原文地址:https://www.cnblogs.com/nxzblogs/p/11245636.html