미리수얌 블로그

LeetCode: Remove Duplicates from Sorted Array 본문

코딩문제풀이/Leetcode

LeetCode: Remove Duplicates from Sorted Array

미리수얌 2018. 9. 25. 08:58

LeetCode: Remove Duplicates from Sorted Array

정렬된 배열이 주어졌을때 똑같은 숫자를 In-Place 로 없에고 길이를 리턴하시오. 예를 들어 [1, 1, 2, 3, 4, 5, 5, 6] 이 주어 졌으면 이것을
[1, 2, 3, 4, 5, 6, ?, ?] 로 바꾸고 (뒤에 ? 에는 무슨 숫자가 와도 무방) 그 다음 6 을 리턴.
다른 예로는 [1, 1, 1, 1, 2] => [1, 2, ?, ?, ?] 그리고 2를 리턴

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int noDupIndex = 1;
    for (int i = 1; i < nums.length; ++i) {
        if (nums[i] != nums[i - 1]) {
            nums[noDupIndex++] = nums[i];
        }
    }
    return noDupIndex;
}


'코딩문제풀이 > Leetcode' 카테고리의 다른 글

LeetCode: Remove Nth Node From End of List  (0) 2018.09.25
LeetCode: Letter Combinations of a Phone Number  (0) 2018.09.25
Valid Parentheses  (0) 2018.09.25
Add Two Numbers  (0) 2018.09.23
Two Sum  (0) 2018.09.21
Comments