码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 5

时间:2019-04-21 22:56:49      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:key   htable   第一个   判断   nbsp   amp   依次   循环   ber   

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 }

 

Leetcode 5

标签:key   htable   第一个   判断   nbsp   amp   依次   循环   ber   

原文地址:https://www.cnblogs.com/Afei-1123/p/10747552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!