상세 컨텐츠

본문 제목

Arrays 101 Code from Java to Go(A Better Repeated Deletion Algorithm - Answer)

Go/Leet Code

by Gopythor 2022. 3. 10. 17:27

본문

728x90
반응형

Code

Java

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;
}

Go

func removeDuplicates(nums []int) int {
    // Check for edge cases.
    if nums == nil {
        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.
    var writePointer int = 1
    // Go through each element in the Array.
    for readPointer := 1; readPointer < len(nums); readPointer++ {
        // If the current element we're reading is *different* to the previous
        // element...
        if nums[readPointer] != nums[readPointer-1] {
            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
}
728x90
반응형

관련글 더보기

댓글 영역