zoukankan      html  css  js  c++  java
  • 二维数组中查找 有序数组合并 效率O(n)

    新类型矩阵:

    1    2    3   4   5

    6    7   8   9   10

    11 12  13 14 15

    16 17  18 19  20

    查找一个指定数据是否在矩阵中

    #include <iostream>
    using namespace std;
    bool Find(int* matrix, int row, int colum, int num);
    
    int main()
    {
    int matrixOne[12] = {1,2,3,4,5,6,7,8,9,10,11,12};
    int* matrixTwo = NULL;
    bool bl =Find(matrixOne, 3, 4,-3);
    
    if (bl)
    {
    cout<<"find it"<<endl;
    }
    else
    cout<<"cann't find it"<<endl;
    return 0;
    }
    
    bool Find(int* matrix, int row, int colum, int num)
    {
    
    /////左下角
    bool fund = false;
    if ((matrix == NULL) || (row <=0 )|| (colum<=0))
    {
    return fund;
    }
    if (num < matrix[0] || num >matrix[row*colum -1])
    {
    return fund;
    }
    int r = row -1;
    int col = 0;
    while ((r >=0) &&(col < colum))
    {
    if (matrix[r*colum +col] == num)
    {
    fund = true;
    cout<<"row = "<< r<<endl;
    cout<<"colum =" <<col<<endl;
    return fund;
    }
    else if (matrix[r*colum +col] < num)
    col++;
    else
    r--;
    }
    return fund;
    }

    合并两个数组(包括字符串)时,如果从前往后复制每个数字(或字符)需要移动多次,那么我们可以考虑从后往前复制,从而减少移动次数,提高效率

    例如:两个连续的数组A1和A2,内存在A1的末尾有足够空间可以容纳A2。请实现一个函数,把A2中的所有数字插入到A1中并且所有的数字是排序的。

    #include <iostream>
    #include <string>
    using namespace std;
    void CombineArray(int destr[], int sostr[], int dLen, int sLen);
    #define MAX_SIZE 100
    #define MIN_SIZE 50
    
    int main()
    {
    int dlen = 5;
    int slen = 4;
    int desArray[MAX_SIZE] = {1, 3, 5, 7, 9};
    int sorArray[MIN_SIZE] = {2, 4, 6, 8};
    CombineArray(desArray, sorArray, dlen, slen );
    for (int i=0; i<dlen+slen; i++)
    {
    cout<<desArray[i]<<" ";
    }
    cout <<endl;
    return 0;
    }
    
    void CombineArray(int deArray[], int soArray[], int dLen, int sLen)
    {
    if ((deArray == NULL) || (soArray == NULL) || (dLen <=0) || (sLen <=0))
    {
    return;
    }
    if (MAX_SIZE < dLen + sLen)
    {
    return;
    }
    int totalLen = dLen + sLen -1;
    int i_spnt = sLen - 1;
    int i_dpnt = dLen - 1;
    while((i_dpnt>=0) && (i_spnt >=0))
    {
    if (deArray[i_dpnt] > soArray[i_spnt])
    {
    deArray[totalLen--] = deArray[i_dpnt--];
    }
    else
    {
    deArray[totalLen--] =soArray[i_spnt--];
    }
    }
    while(i_dpnt >=0)
    {
    deArray[totalLen--] = deArray[i_dpnt--];
    }
    while(i_spnt >= 0)
    {
    deArray[totalLen--] =soArray[i_spnt--];
    }
    return ;
    }
    博客内容只为本人学习所感转载亦或自写,不足或错误之处请大家不吝赐教
  • 相关阅读:
    MySQL 数据库报错 Too many connections
    C# 字符串倒序输出
    C# Guid.NewGuid()
    C# MongoDB 查询所有集合名
    MongoDB 错误be UuidLegacy, not UuidStandard
    jstree 反选,测试400条数据左右有点卡
    js Date对象日期格式化
    敏捷开发-Scrum
    linux centos7 和 windows下 部署 .net core 2.0 web应用
    部署SSL站点 IIS+asp.net
  • 原文地址:https://www.cnblogs.com/niupan369/p/4495442.html
Copyright © 2011-2022 走看看