zoukankan      html  css  js  c++  java
  • 计数思想(类似于hash值)

    //判断数组中是否有重复元素,最直接的思路是用双层循环判断(O(n ^ 2));
    //也可以先排序,后比较,但基于比较的排序时间复杂度至少为O(n*logn).
    //所以,这些思路都不行。根据题目的限制条件,很容易想到用计数排序,时间复杂度为O(n),这当然满足题意,但是,把计数排序用在此处,无疑是大材小用了。
    //在计数排序中,有一个关键的步骤是计数,本题就可以利用计数排序中的计数思想(有点类似于哈希),程序代码如下:

    #include<iostream>
    using namespace std;

    void print(bool b)
    {
    if (b)
    cout << "yes" << endl;
    else
    cout << "no" << endl;
    }
    typedef struct Hashtable
    {
    int value;
    int count;
    }hash;
    bool hasTheSameNumber(int a[], int n)
    {
    int *p = new int[n];
    //int *p=new hash[n];
    int i;
    for (i = 0; i < n; i++) //置0
    {
    p[i] = 0;
    }
    for (i = 0; i < n; i++) //开始计数
    {
    p[a[i] - 1]++;
    //p[i].value=a[i]%n;
    //p[i].count++;
    }
    for (i = 0; i < n; i++)
    if (p[i] > 1) //有重复 //p[i].count
    return true;
    delete[] p;

    return false;
    }

    int main()
    {
    int a[] = { 1, 3, 4, 2, 5 };
    int b[] = { 1, 6, 2, 3, 4, 1 };

    print(hasTheSameNumber(a, 5));
    print(hasTheSameNumber(b, 6));
    return 0;
    }

  • 相关阅读:
    清理iOS工程里无用的图片,可瘦身ipa
    NSTimer内存泄漏导致控制器不调用dealloc
    iOS面试题 -总结 ,你的基础扎实吗?
    Xcode找不到模拟器出现"My Mac"
    前端开发
    并发编程&数据库
    数据库
    4.2
    4.5
    4.4
  • 原文地址:https://www.cnblogs.com/xcb-1024day/p/11334861.html
Copyright © 2011-2022 走看看