sort-colors&Remove Duplicates from Sorted Array

题目来源: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 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].

思路:同上

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;
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值