Leetcode/Top Interview 150

Array - Remove Duplicates from Sorted Array

자전거통학 2021. 5. 23. 21:58

https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

Notes

  •   정렬된 배열이 인풋임.
  •   추가 메모리 공간을 사용하면 안됨.
  •   배열 길이를 직접 수정하는 것이 아니고, 배열을 수정하고 바르게 읽기 위해 길이 또한 반환

 

public class Solution {
    public int RemoveDuplicates(int[] nums) {   // [1, 1, 2]
        if(null == nums)    return 0;
        if(1 >= nums.Length)
            return nums.Length;
        int head = 0;
        for(int tail = 1; tail < nums.Length; ++tail)
        {
            if(nums[head] != nums[tail])   
            {
                ++head; 
                nums[head] = nums[tail];
            }
        }
        return head+1;
    }
}

 

'Leetcode > Top Interview 150' 카테고리의 다른 글

[Array/String][Easy] 27. Remove Element  (0) 2024.04.28
[Array/String][Easy] 88. Merge Sorted Array  (0) 2024.04.28
Contains Duplicate  (0) 2021.06.02
Array - Rotate Array  (0) 2021.05.27
Array - Best Time to Buy and Sell Stock II  (0) 2021.05.23