Leetcode: 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.

public class Solution {
    public int removeElement(int[] A, int elem) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(A==null||A.length==0){
            return 0;
        }
        
        int start = 0;
        int end = A.length-1;
        while(start<=end){
            if(A[start]==elem){
                swap(A,start,end);
                end--;
            }else{
                start++;
            }
        }
        return end+1;
    }
    
    public void swap(int[] num,int i, int j){
        int tmp = num[i];
        num[i]=num[j];
        num[j]=tmp;
    }
}
FacebookTwitterGoogle+Share

Leetcode: Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

public class Solution {
    public void nextPermutation(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(num==null||num.length<=1){
            return;
        }

        int i=num.length-2;
        while(i>=0 && num[i]>=num[i+1]){
            i--;
        }
        if(i==-1){
            int m = 0;
            int n = num.length-1;
            while(m<n){
                swap(num,m,n);
                m++;
                n--;
            }

        }else{
            int minIndex = i+1;
            for(int j=minIndex+1;j<num.length;j++){
                if(num[j]>num[i] && num[j]<num[minIndex]){
                    minIndex=j;
                }
            }
            swap(num,i,minIndex);

            for(int k=i+1;k<num.length;k++){
                minIndex = k;
                for(int l=k+1;l<num.length;l++){
                    if(num[l]<num[minIndex]){
                        minIndex=l;
                    }
                }
                swap(num,k,minIndex);
            }
        }

    }

    public void swap(int[] num, int i, int j){
        int tmp = num[i];
        num[i] = num[j];
        num[j] = tmp;
    }

}