算法初始记录

1.Remove Element

       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.
 

题意:在一个数组里面移除指定value,并且返回新的数组长度。

//import java.util.Scanner;
class Solution {
    public static void main(String[] args){

        int[] num = {1,2,2,3,4,5};
        int y=Removement(num,num.length,2);
        System.out.println(y);

    }
     public static int Removement(int A[], int m, int elem) {
        int i = 0;
        int j = 0;
        for (i = 0; i < m; i++) {
            if (A[i] == elem) {
                continue;
            }

            A[j] = A[i];
            j++;

        }
        return j;

    }

}

第一次的代码写出来,运行不出来,老是输出异常,对于函数参数对于数组的调用还有有点没有搞懂,还是等过一段时间我在看吧

下一题

下一题

2.Remove    Duplicates    from    Sorted    Array

Follow    up    for    "Remove    Duplicates":    What    if    duplicates    are    allowed    at    most    twice?
For    example,    Given    sorted    array    A    =    [1,1,1,2,2,3],
Your    function    should    return    length    =    5,    and    A    is    now    [1,1,2,2,3].
紧接着上一题,同样是移除重复的元素,但是可以允许最多两次重复元素存在。

public class Solution2 {
    public static void main(String[] args){
        int a[]={1,1,1,2,2,3,0,3};
        int x=removeDuplicates(a,a.length);
        System.out.println(x);
    }
    public static int removeDuplicates(int A[],int n){
        if(n==0){
            return 0;
        }
        int j=0;
        int num=0;
        for(int i=1;i<n;i++){
            if(A[j]==A[i]){
                num++;
                if(num<2){
                    A[++j]=A[i];
                }
                else{
                    A[++j]=A[i];
                    num=0;
                }
            }
        }
        return j+1;
    }
}

3.Plus    One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

将一个数字的每个位上的数字分别存到一个一维向量中,最高位在最开头,我们需要给这个数字加一,即在末尾数字加一,如果末尾数字是9,那么则会有进位问题,而如果前面位上的数字仍为9,则需要继续向前进位。具体算法如下:首先判断最后一位是否为9,若不是,直接加一返回,若是,则该位赋0,再继续查前一位,同样的方法,知道查完第一位。如果第一位原本为9,加一后会产生新的一位,那么最后要做的是,查运算完的第一位是否为0,如果是,则在最前头加一个1。代码如下:

public class Soultion3 {
    public void main(String[] args]){

    }
    public int[] plusOne(int[] digits){
        int n=digits.length;
        for(int i=digits.length-1;i>=0;--i){
            if(digits[i]<0){
                ++digits[i];
                return digits;
            }
            digits[i]=0;
        }
        int [] res=new int[n+1];
        res[0]=1;
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/However_day/article/details/83305011
今日推荐