码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Remove Duplicates from Sorted Array && Remove Element

时间:2014-06-06 06:53:19      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:c   class   code   a   ext   int   

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 A = [1,1,2],

Your function should return length = 2, and A is now[1,2].

这道题用了2个指针,一个i指向数组的值,一个newlength是指向未重复的数值的个数。

遍历数组时,当发现相同的值时,将i一直向后移动到不同值为止。同时将这个不同值移动到newLength的位置。最后返回newLength的值。

一开始在第二个循环忘记检查i值是否超出边界,导致了一次错误。


public class Solution { 
     public int removeDuplicates(int[] A) { 
        int length = A.length; 
        if(length == 0||length == 1)return length; 
        int newLength = 1; 
        int i = 1; 
        int val = A[0]; 
        while(i<length) 
        { 
            if(A[i]!=val) 
            { 
                if(i != newLength) 
                { 
                    A[newLength] = A[i]; 
                } 
                val = A[i]; 
                i++; 
                newLength++; 
            } 
            else 
            { 
                int temp = i; 
                i = i+1; 
                while(i<length&&A[i] == val) 
                { 
                    i = i+1; 
                } 
                if(i!=length) 
                { 
                    A[newLength] = A[i]; 
                    val = A[i]; 
                    i++; 
                    newLength++; 
                } 
            } 
            
        } 
        return newLength; 
    } 
}

  Given an array and a value, remove all instances of that value in place and return the new length.

  The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.

其实原理和上面一样,遍历一遍数组,把要删除的元素删除,讲后面的非删除元素向前移动。


public class Solution {
  public int removeElement(int[] A, int elem) {
    int length = A.length;
    if(length == 0)return length;
    int newLength = 0;
    int i = 0;
    while(i<length)
    {
      if(A[i]!=elem)
      {
        if(i!=newLength)
        {
          A[newLength] = A[i];
        }
        i++;
        newLength++;
      }
      else
      {
        i++;
      }
    }
    return newLength;
  }
}

 

 

 

 

LeetCode:Remove Duplicates from Sorted Array && Remove Element,布布扣,bubuko.com

LeetCode:Remove Duplicates from Sorted Array && Remove Element

标签:c   class   code   a   ext   int   

原文地址:http://www.cnblogs.com/jessiading/p/3767709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!