LeetCode - 26. Remove Duplicates from Sorted Array(Array, Two Pointers)*

YAMAMAMO·2022년 2월 6일
0

LeetCode

목록 보기
17/100

문제

파파고번역
정수 배열 번호가 내림차순이 아닌 순서로 정렬되면 중복 요소를 제거하여 각 고유 요소가 한 번만 나타나도록 합니다. 원소의 상대적 순서는 동일하게 유지되어야 합니다.
일부 언어에서는 배열 길이를 변경할 수 없으므로 결과를 배열 번호의 첫 번째 부분에 배치해야 합니다. 더 형식적으로, 중복을 제거한 후에 k개의 원소가 있다면, 숫자의 첫 번째 k개의 원소는 최종 결과를 가져야 한다. 첫 번째 k 원소 뒤에 무엇을 남겨두든 중요하지 않습니다.
첫 번째 k개의 숫자 슬롯에 최종 결과를 넣은 후 k를 반환합니다.
다른 배열에 추가 공간을 할당하지 마십시오. O(1) 추가 메모리로 입력 배열을 수정하여 이 작업을 수행해야 합니다.

https://leetcode.com/problems/remove-duplicates-from-sorted-array/

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.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of nums.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,,,,,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

풀이

자바입니다.

  • 배열의 길이가 0이면 0을 리턴한다.
  • i 위치를 기준으로 한다.
  • nums[i]와 nums[j]가 다르다면 i++, nums[i]=nums[j] 를 한다.
class Solution {
    public int removeDuplicates(int[] nums) {
            if (nums.length == 0) {
                 return 0;
            }else{
                int i = 0;
                for (int j = 1; j < nums.length; j++) {
                    if (nums[j] != nums[i]) {
                        i++;
                        nums[i] = nums[j];
                    }
                }
                return i + 1;
            }
        }
}
profile
안드로이드 개발자

0개의 댓글