sort-colors&Remove Duplicates from Sorted Array

来源:互联网 发布:手机验证码php源码 编辑:程序博客网 时间:2024/06/05 11:21

题目来源:Leetcode

1.Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively

自己思路:因为只有三个颜色,分别由0,1,2代表,第一次统计三种颜色的数量,第二次按照数量放进去(感觉投机取巧)
public class Solution {    public void sortColors(int[] A) {        int ones=0,twos=0,zero=0;        for(int i=0;i<A.length;i++)            {            if(A[i]==0)                zero++;            else if(A[i]==1)                ones++;            else                twos++;        }        for(int i=0;i<zero;i++)            A[i]=0;        for(int i=zero;i<zero+ones;i++)            A[i]=1;        for(int i=zero+ones;i<A.length;i++)            A[i]=2;            }}
leetcode上思路:一次遍历是0就放前边是二就放后边(也没啥)
public class Solution {public void sortColors(int[] nums) {    // 1-pass    int p1 = 0, p2 = nums.length - 1, index = 0;    while (index <= p2) {        if (nums[index] == 0) {            nums[index] = nums[p1];            nums[p1] = 0;            p1++;        }        else if (nums[index] == 2) {            nums[index] = nums[p2];            nums[p2] = 2;            p2--;            index--;        }        index++;    }}}

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

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

思路:同上

public class Solution {    public int removeDuplicates(int[] A) {        int temp=0;        if(A.length==0)            return 0;        if(A.length==1)            return 1;        for(int i=0;i<A.length;i++){            if(i<A.length-1){                if(A[i]!=A[i+1]){                    temp++;                    A[temp]=A[i+1];                                    }            }        }        return temp+1;            }}


原创粉丝点击