[LeetCode]Remove Duplicates from Sorted Array

오트밀·2022년 1월 21일
0
class Solution {
    public int removeDuplicates(int[] nums) {
        int index = 1;
        for(int i = 0; i < nums.length-1; i++){
           if(nums[i] != nums[i+1]){
                nums[index] = nums[i+1];
               index++;
           } 
        }
        return index;
    }
}

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

내림차순이 아닌 integer배열 nums가 주어진다. 기존 배열의element가 중복된다면 삭제해서 유일하게 만들어라. 배열의 순서는 그대로 유지되어야한다.

바로 전에 풀었던 Remove Element와 유사한 로직이라 쉽게 풀었다.

https://velog.io/@daily_d/LeetCodeRemove-Element

이건 LeetCode 에서 제공하는 풀이방식

public int removeDuplicates(int[] nums) {
        
  // Check for edge cases.
  if (nums == null) {
      return 0;
  }
  
  // Use the two pointer technique to remove the duplicates in-place.
  // The first element shouldn't be touched; it's already in its correct place.
  int writePointer = 1;
  // Go through each element in the Array.
  for (int readPointer = 1; readPointer < nums.length; readPointer++) {
      // If the current element we're reading is *different* to the previous
      // element...
      if (nums[readPointer] != nums[readPointer - 1]) {
          // Copy it into the next position at the front, tracked by writePointer.
          nums[writePointer] = nums[readPointer];
          // And we need to now increment writePointer, because the next element
          // should be written one space over.
          writePointer++;
      }
  }
  
  // This turns out to be the correct length value.
  return writePointer;
}

엣지 케이스(edge case): 알고리즘이 처리하는 데이터 값이 알고리즘의 범위를 넘어가는 경우 발생하는 문제

중요 포인트는 writePointer가 readPointer에 앞서서 배열을 읽을 수 없다는 점이다.이건 아직 읽지 못한 요소를 덮어쓸 수 없다는 뜻이다.

profile
루틴을 만들자

0개의 댓글