zoukankan      html  css  js  c++  java
  • 02-对不重复的一组数据查找

    假如10个学生数据(学号 成绩)不重复,查找数据的思路:

    1.从头到尾顺序遍历。O(N)

    2.排序后,二分查找。O(logN)

    3.建立索引,直接定位。O(1)

     

    如何建立索引?

    此处假设学生学号数据类型int,范围【0,100】。

    学生的学号作为数据存放数组的索引下标。

    实际情况中,学号往往以字符串方式存在,数据也多位于文件中,则可以将字符串和文件中地址位置进行关联。查找时,通过字符串查找到文件地址,进而直接获取数据即可。因为学号具有唯一性,所以将学号和地址作为一对hash值进行存储即可。或者按照学号进行排序存储,搜索按照二分查找学号,进而找到对应的地址(文件中的位置或者内存中的位置),进而快速获取对应的数据。此方法适用于大数据量的预处理。

     

    #include <iostream>

    #include <memory>

    #include <string>

    #include "StringTools.h"

    using namespace std;

     

    struct StStudent

    {

        string no;

        int score;

    };

     

    void printStudent(const StStudent& student)

    {

        cout<<"student "<<student.no<<" "

            <<"score: "<<student.score<<endl;

    }

     

    // 10 23 34 83 28 25 82 73 92 13

    int main()

    {

        const int INVALIDATE_INDEX = -1;

        // create index when read data

        int data_index[101];

        memset(data_index,INVALIDATE_INDEX,sizeof(data_index));

     

        StStudent arr[10];

        // start read data

        int tmp[10] = {10,23,34,83,28,25,82,73,92,13};

        for (int i= 0; i<10; ++i)

        {

            StStudent student;

            student.no = StringTools::toString(tmp[i]);

            student.score = i*10+5// score assignment

            arr[i] = student;

            // build index for item

            data_index[tmp[i]] = i;

        }

        // 1.input find NO.

        int findNo = 34;

        // 2.find index

        int findIndex = data_index[findNo];

        if (findIndex == INVALIDATE_INDEX)

        {

            cout<<"can not find NO."<<endl;

        }

        else

        {

            StStudent findItem = arr[findIndex];

            printStudent(findItem);

        }

     

        return 0;

    }

    student 34 score: 25

    Program ended with exit code: 0

     

     

     

     

  • 相关阅读:
    APP设计资源
    browsersync实现网页实时刷新(修改LESS,JS,HTML时)
    Browsersync + Gulp.js
    用原生js对表格排序
    js深复制
    c++刷题(43/100)矩阵旋转打印
    将本地的mongodb迁移到阿里云
    c++刷题(39/100)笔试题3
    c++刷题(37/100)笔试题2
    c++刷题(33/100)笔试题1
  • 原文地址:https://www.cnblogs.com/sharpfeng/p/5141956.html
Copyright © 2011-2022 走看看