题目链接
    image.png

    1. class Solution {
    2. // 1.我的方法
    3. public int removeDuplicates1(int[] nums) {
    4. int left=0,right=0;
    5. int len = nums.length;
    6. while(left < len) {
    7. if(left > 0 && nums[left] == nums[left-1]) {
    8. left++;
    9. } else {
    10. if(left != right) {
    11. nums[right] = nums[left];
    12. right++;
    13. left++;
    14. } else {
    15. left++;
    16. right++;
    17. }
    18. }
    19. }
    20. return right;
    21. }
    22. // 2.老师的
    23. public int removeDuplicates2(int[] nums) {
    24. if(nums.length == 0) {
    25. return 0;
    26. }
    27. int i = 0;
    28. for(int j = 1; j < nums.length; j++) {
    29. if(nums[j]!= nums[i]) {
    30. i++; // 快指针往后移动
    31. nums[i] = nums[j];
    32. }
    33. }
    34. return i+1;
    35. }
    36. // 3.我的方法,调整
    37. public int removeDuplicates(int[] nums) {
    38. int right=1,left=0;
    39. int len = nums.length;
    40. while(right < len) {
    41. if(nums[left] == nums[right]) { // 相等的时候右边的指针进行移动
    42. right++;
    43. } else { // 不相等的时候,将左指针向右移动一位,再进行赋值。如果是相同位置的话,等于重复赋值,不用关心。
    44. left++;
    45. nums[left] = nums[right];
    46. right++;
    47. }
    48. }
    49. return left+1;
    50. }
    51. }