26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

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 new length.

題意:

給定一個排序後的數組,將重複的元素去除,只留下一個,例如:[1,2,3,4,4]->[1,2,3,4],並在去除後返回去重後元素的大小

題解:

這題是將數組中一樣的元素去除,故有兩個指針:

  1. 指向目前元素(i)
  2. 指向目前沒有重複的元素(j)

指針: i, j 不含有重複元素的數組指針
ex1:                           ex2: 
======================================
step1 i = 1; j = 0 j++ | step1 i = 1; j = 0 j++
      1,1,1,2,3,4          |       1,2,3,3,4  
step2 i = 2; j = 0       | step2 i = 2; j = 1 j++
      1,1,1,2,3,4          |       1,2,3,3,4 
step3 i = 3; j = 1 j++ | step3 i = 3; j = 2
      1,2,1,2,3,4          |       1,2,3,3,4
step4 i = 4; j = 2 j++ | step4 i = 4; j = 2 j++
      1,2,3,2,3,4          |       1,2,3,4,4
step5 i = 4; j = 3 j++
      1,2,3,4,3,4    
step6 i = 5; j = 4 j++
      1,2,3,4,3,4
返回j指針,表示去重後的元素大小

package LeetCode.Easy;
/*
 * 這題是將數組中一樣的元素去除,故有兩個指針:
 * 1.指向目前元素(i)
 * 2.指向目前沒有重複的元素(j)
 * 
 * 
指針: i, j 不含有重複元素的數組指針
ex1:                     ex2: 
======================================
step1 i = 1; j = 0 j++ | step1 i = 1; j = 0 j++
      1,1,1,2,3,4      |       1,2,3,3,4  
step2 i = 2; j = 0     | step2 i = 2; j = 1 j++
      1,1,1,2,3,4      |       1,2,3,3,4 
step3 i = 3; j = 1 j++ | step3 i = 3; j = 2
      1,2,1,2,3,4      |       1,2,3,3,4
step4 i = 4; j = 2 j++ | step4 i = 4; j = 2 j++
      1,2,3,2,3,4      |       1,2,3,4,4
step5 i = 4; j = 3 j++
      1,2,3,4,3,4    
step6 i = 5; j = 4 j++
      1,2,3,4,3,4
 *      返回j指針,表示去重後的元素大小
 */

public class RemoveDuplicatesFromSortedArray {
    public int removeDuplicates(int[] nums) {
    	//這個指針指向目前沒有重複的元素
        int j = 0;
        
        //歷遍數組所有元素(這種題可以從統一從1比較)
        for(int i = 1; i < nums.length; i ++) {
            if(nums[i] == nums[j]) {
            	//使指針j不更新
                continue;
            }
            j ++;
            nums[j] = nums[i];
        }
        
        //返回去重後的數組長度
        return j + 1;
    }

}





                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值