search

Home  >  Q&A  >  body text

Java - Looking for an explanation of the following algorithm

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

扔个三星炸死你扔个三星炸死你2724 days ago1104

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-07-05 10:28:05

    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
        }

    reply
    0
  • 世界只因有你

    世界只因有你2017-07-05 10:28:05

    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.

    reply
    0
  • Cancelreply