C++ STL之set函数

C++中的set函数是在leetcode中的202.Happy Number中遇到的。

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
     1 class Solution {
     2 public:
     3     bool isHappy(int n) {
     4         vector<int> numStore;
     5         set<int> processed;
     6         while(n!=1&&processed.insert(n).second)
     7         {
     8          
     9             int sum = 0;
    10             while(n>0){
    11                 sum+=(n%10)*(n%10);
    12                 n=n/10;
    13             }
    14             n = sum;
    15         }
    16         return n==1;
    17        
    18     }
    19 };
  • 在本题中,通过判断将数据存储到set结构中,借助set函数中元素的唯一性,判断其是否再次出现。
  • 在set容器中,每个在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序。同时set中的值不能被改变

  • C++的STL中的vector封装数组,list封装了链表,map和set封装了二叉树
  • 由于不需要做内存拷贝,仅仅是指针的移动,因此map和set的插入删除效率比其他容器要高。

当数据元素增多时,set的插入和搜索速度变化如何?

如果你知道log2的关系你应该就彻底了解这个答案。在set中查找是使用二分查找,也就是说,如果有16个元素,最多需要比较4次就能找到结果,有32个元素,最多比较5次。那么有10000个呢?最多比较的次数为log10000,最多为14次,如果是20000个元素呢?最多不过15次。看见了吧,当数据量增大一倍的时候,搜索次数只不过多了1次,多了1/14的搜索时间而已。你明白这个道理后,就可以安心往里面放入元素了。

原文地址:https://www.cnblogs.com/timesdaughter/p/5323786.html