Java - Looking for an explanation of the following algorithm
扔个三星炸死你
扔个三星炸死你 2017-07-05 10:26:05
0
2
1071

It is known that the linear table A of length n adopts a sequential storage structure. Please write an algorithm with a time complexity of O(n) and a space complexity of O(1). This algorithm deletes all items whose values ​​​​are in the linear table. data elements.

void  Delete(ElemType A[ ],int  n)
∥A是有n个元素的一维数组,本算法删除A中所有值为item的元素。
{i=1;j=n;∥设置数组低、高端指针(下标)。
 while(i<j)
   {while(i<j && A[i]!=item)i++;         ∥若值不为item,左移指针。
    if(i<j)while(i<j && A[j]==item)j--;∥若右端元素为item,指针左移
    if(i<j)A[i++]=A[j--];}

It cannot run after rewriting. The following is the rewritten

package 线性表;

public class Work_10 {
    public Work_10(){
        int[] arr={2,34,4,4,5};
        int item=4;
        delete(arr,item,arr.length-1);
        for(int a:arr){
            System.out.print(a+" ");
        }
    }
    public static void delete(int[] array,int item,int n){
        int i=0,j=n;
        while(i<j){
            while(i<j&&array[i]!=item) i++;
            if(i<j) while(i<j&&array[j]==item) j--;
            if(i<j){
                array[i++]=array[j--];
            }
        }
    }
    public static void main(String[] args) {
        new Work_10();
    }
}

Don’t know how to change it?
Please explain, sir

扔个三星炸死你
扔个三星炸死你

reply all(2)
淡淡烟草味

If you want to delete, search first, then delete. I will give you a search, and you can think of the rest and write a variant.

public static int search(byte[] a,int n, byte item) {
        int low = 0;
        int high = n - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            byte midVal = a[mid];

            if (midVal < item)
                low = mid + 1;
            else if (midVal > item)
                high = mid - 1;
            else
                return mid; // 找到item
        }
        return -(low + 1); // 没找到item
    }
世界只因有你

Oh, the extra number is because the number you output is wrong. The deletion process is fine.

Before deletion, the content of your array is 2,34,4,4,5, a total of 5 elements.

The content to be deleted is 4, which means that there are only 3 elements left after deletion, which are 2,34,5

So your result output only needs to output the first 3 elements of the array, and the last two are invalid elements.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!