26. 27. Remove Duplicates from Sorted Array

来源:互联网 发布:崖山之后无华夏 知乎 编辑:程序博客网 时间:2024/06/09 20:16

26.  Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 ofnums being1 and 2 respectively. It doesn't matter what you leave beyond the new length.


思路: 设置两个指针,从开始遍历,时间复杂度为O(N).

<span style="font-size:14px;">public int removeDuplicates(int[] nums) {        if(nums==null)            return 0;        int len=nums.length;        int start=0,now=1;        for(;now<len;){            while(now<len&&nums[now]==nums[start])                now++;            if(now==len)                return start+1;            nums[start+1]=nums[now];            now++;            start++;        }        return start+1;            }</span>


27. Remove Element

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

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

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

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements ofnums being 2.



思路: 设置两个指针,从开始遍历,若等于给定值,则跳过; 时间复杂度为O(N).

public int removeElement(int[] nums, int val) {        if(nums==null)            return 0;        int len=nums.length;        int p1=-1,p2=0;        for(;p2<len;p2++){            while(p2<len&&nums[p2]==val){                p2++;            }            if(p2==len)                return p1+1;            nums[p1+1]=nums[p2];            p1++;                    }        return p1+1;    }
上述实现数组移动的次数较多,为了避免大量移动数据,设置2个指针,分别指向数组的头和尾,把尾部不等于val的数放到头部等于val的位置.减少数据移动次数.

public int removeElement(int[] nums, int val) {         if(nums==null)             return 0;         int len=nums.length;         int p1=0,p2=len-1;         while(p1<=p2){             while(p1<=p2&&nums[p1]!=val)                 p1++;             if(p1>p2)                 return p1;             while(p2>=p1&&nums[p2]==val){                 p2--;             }             if(p1>p2)                 return p1;             nums[p1++]=nums[p2--];                      }                  return p1;     }


0 0
原创粉丝点击