8.6 algorithm interview questions

1: one to be re-ordered array and returns the length of the array after deduplication

Algorithm works:

Not required to develop a new space, traverse a double pointer

Using two indices i and j to traverse, wherein the recording position of the last element i obtained after the de-emphasis of the new array, used to traverse the entire array j, i and j leading to move,

  • j to move, when the same location j elements and element location i, i Fixed
    • Inconsistent i + = 1 to j element is copied into a location where the position i
int removeDuplicates(int A[]){
    int i = 0; //第一个指针
    int j;// 第二个指针
    int n = A.length;
    if(n <= 1) return n;
    for(j = 1; j < n;j++){
        if(A[j]!=A[i]){ // 若两个指针所指元素不同,则i+1位置保存j所指元素的值
            A[++i] = A[j]
        }
    }
    return i+1 //返回新数组的长度
    
}

Guess you like

Origin www.cnblogs.com/rise0111/p/11309879.html