zoukankan      html  css  js  c++  java
  • Leetcode 5

    HashTable Easy

    1. 136. Single Number

       0与0异或是0,1与1异或也是0,那么我们会得到0

    1 class Solution {
    2 public:
    3     int singleNumber(vector<int>& nums) {
    4         int res = 0;
    5         for( auto num : nums) res ^= num;
    6         return res;
    7     }
    8 };

    2. 202. Happy Number

      用 HashSet 来记录所有出现过的数字,然后每出现一个新数字,在 HashSet 中查找看是否存在,若不存在则加入表中,若存在则跳出循环,并且判断此数是否为1,若为1返回true,不为1返回false

     1 class Solution {
     2 public:
     3     bool isHappy(int n) {
     4         unordered_set<int> st;
     5         while(n != 1){
     6             int sum = 0;
     7             while(n){
     8                 sum += ( n % 10) * ( n % 10);
     9                  n /= 10;
    10             }
    11             n = sum;
    12             if(st.count(n)) 
    13                 break;
    14             st.insert(n);
    15         }
    16         return n == 1;
    17     }
    18 };

    3. 204. Count Primes

      大概步骤为,第一次筛选2的倍数的数字,将其都筛选出去,第二轮筛选3的倍数的数字,筛选后,剩下的第一个数字就是5(因为4在第一次筛选的时候作为2的倍数已经筛出去)第三轮则筛选5倍数的数字,第四轮7倍数,第五轮11倍数……依次筛选下去,筛n轮。

     1 class Solution {
     2 public:
     3     int countPrimes(int n) {
     4         int res = 0;
     5         vector<bool> prime(n,true);
     6         for(int i = 2; i < n ; i++){
     7             if(prime[i])
     8                 res++;
     9             for(int j = 2; i*j < n; j++){
    10                 prime[i*j] = false;
    11             }
    12         }
    13         return res;
    14     }
    15 };

    4. 290. Word Pattern

      map.put(),返回的值是与当前key相同的值所对应的value,也就是之前出现过key值的编号。返回的是一个对象用Integer。

     1 class Solution {
     2     public boolean wordPattern(String pattern, String str) {
     3        String[] words = str.split(" ");
     4         if(words.length != pattern.length())
     5             return false;
     6         Map index = new HashMap();
     7         for(Integer i=0; i<words.length; i++){
     8             if( index.put(pattern.charAt(i), i) != index.put(words[i],i))
     9                 return false;
    10         }
    11         return true;
    12     }
    13 }
  • 相关阅读:
    数据库从别的数据库查询一张表在插入到新的数据库里面
    html5 学习随笔 1
    .net MVC 学习笔记 (一)
    Html5 本地存储
    .net MVC 学习笔记 (二)
    蝙蝠侠解救罗宾的问题
    求职的第一面Harman
    求职第七面——烽火通讯
    求职的第二面—Samsung
    求职第六面——瑞星微电子
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/10747552.html
Copyright © 2011-2022 走看看