您好,欢迎来到花图问答。
搜索
您的当前位置:首页查找问题

查找问题

来源:花图问答

1.有序数列的查找

完全写对也不容易,注意循环条件,输入的数列是从小到大的有序序列

#include <iostream>
using namespace std;
int BinarySearch(int a[],int n,int value)
{
    if(n<=0) return -1;
    if(n==1&& a[0]==value) return 0;
    int left=0,right=n-1;
    int mid;
    while(left<=right)//跟边界条件配合
    {
        mid= left + ((right-left)>>1);//为了防止溢出
        if(value<a[mid])
            right=mid-1;
        else if(value>a[mid])
            left=mid+1;
        else 
            return mid;
    }
    return -1;
}


void main()
{
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    int x;
    x=BinarySearch(a,10,9);
    cout<<x<<endl;
}

2.行列递增矩阵中的元素查找

#include <iostream>
using namespace std;

bool YounMatrix(int a[][4],int key,int row,int col)
{
    int i=0,j=col-1;
    while(i<row && j>=0)
    {
        if(a[i][j]==key) return true;
        else if(a[i][j]>key && j>0) j--;
        else if(a[i][j]<key && i<row-1) i++;
    }
    return false;
}

void main()
{
    int a[4][4]={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
    if(YounMatrix(a,6,4,4))
        cout<<"found!"<<endl;
    else 
        cout<<"not found!"<<endl;
}

3.找到数组中出现次数超过一半的数

int FindOne(int a[], int n)
{
    int candidate=a[0];
    int count=0;
    for(int i=0;i<n;i++)
    {
        if(candidate==a[i])
            count++;
        else
            count--;
        if(count==0)
        {
            candidate=a[i];
            count=1;
        }
    }
    return candidate;
}

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务