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. public class Solution {
  2. public int RemoveDuplicates(int[] nums) {
  3. List<int> list = new List<int>();
  4. for (int i = 0; i < nums.Length; i++) {
  5. if (i >= 1 && nums[i] != nums[i - 1]) {
  6. list.Add(nums[i]);
  7. }else if (i == 0) {
  8. list.Add(nums[i]);
  9. }
  10. }
  11. for (int i = 0; i < list.Count; i++) {
  12. nums[i] = list[i];
  13. }
  14. return list.Count;
  15. }
  16. }






posted @ 2017-03-01 23:41  xiejunzhao  阅读(121)  评论(0编辑  收藏  举报