26. Remove Duplicates from Sorted Array

inhalin·2021년 2월 22일
0

Leetcode Easy

목록 보기
7/14

문제

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

정렬된 배열 nums가 주어질 때, 주어진 배열에서 중복된 값을 제거해서 각 요소가 한번씩만 나오는 배열의 길이를 반환하라.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.

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 length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.

Constraints:

  • 0 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in ascending order.

Solution

이번 문제도 새로운 배열을 만들지 않고 주어진 배열을 사용해서 풀어야 하는 문제다.

  1. 배열이 null거나 길이가 0이면 0을 반환
  2. 반환할 배열의 길이 len=1로 초기화
  3. 배열의 2번째 요소(nims[1])부터 반복문으로 돌면서 비교하기
  4. len-1번째와 i번째 비교, 같으면 i++
  5. 다르면 len번째에 i번째 값 넣고 len++, i++
class Solution {
    public int removeDuplicates(int[] nums) {
    	if(nums.length == 0 || nums == null) return 0;
    
        int len = 1;
        for (int i = 1; i < nums.length; i++){
            if (nums[len-1]!=nums[i]){
                nums[len]=nums[i];
                len++;
            }
        }
        return len;
    }
}

0개의 댓글