Leet -- 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.


就是在不使用额外空间的情况下,直接修改nums数组,移除重复元素,返回新长度。


思路:
使用两个变量:
front 用于遍历nums数组,从下标0开始,一直往前走
now 仅当nums[now]与nums[front]不等时,now+1,并把nums[now]=nums[front]


最后返回nums[now+1]


实现代码:



public class Solution {
    public int RemoveDuplicates(int[] nums) {
            if(nums == null || nums.Length == 0){
		return 0;
	}
	
	int now = 0;
	int front = 1;
	for(;front < nums.Length; ){
		if(nums[now] != nums[front])
		{
			now ++;
			nums[now] = nums[front];
		}
		front++;
	}
	
	return now + 1;
    }
}


你可能感兴趣的:(Leet -- Remove Duplicates from Sorted Array)