天天看點

1144: 零起點學算法51——數組中删數

Description

在給定的數組中删除一個數 

Input

多組測試,每組第一行輸入1個整數n(n<20),然後是n個整數

第二行輸入1個整數m 

Output

删除在第一行的n個整數中第一次出現數字m并删除,然後按照順序輸出剩下的數,

Sample Input
1144: 零起點學算法51——數組中删數

4 1 2 3 4
3
           

Sample Output

1 2 4

           

HINT

m有可能在原數組中找不到,找不到則輸出原數組

Source

零起點學算法

Code

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int a[n];
        for(int i=0;i<n;i++)
            cin>>a[i];
        int m;
        int t=0;
        cin>>m;
        for(int j=0;j<n;j++)
        {
            if(a[j]==m)
            {
                t=1;
                for(int k=j;k<n;k++)
                    a[k]=a[k+1];
                break;
            }
        }
        for(int i=0;i<n-t-1;i++)
            cout<<a[i]<<" ";
        cout<<a[n-t-1]<<endl;
    }
}
           

因為隻删除第一次出現的數字,是以删除之後一定要break掉

删除即把後面所有的元素都往前推