LeetCode Weekly Contest 117

已經正式在實習了,很久都沒有刷題了(應該有半年了吧),感受仍是不能把思惟鍛鍊落下,因此決定每週末刷一次LeetCode。node

這是第一週(菜的真實,只作了兩題,還有半小時不想看了,冷~)。git

第一題:

965. Univalued Binary Tree

A binary tree is  univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.ide

 

Example 1:spa

Input: [1,1,1,1,1,null,1]
Output: true 

Example 2:code

Input: [2,2,2,5,2]
Output: false 

 

Note:blog

  1. The number of nodes in the given tree will be in the range [1, 100].
  2. Each node's value will be an integer in the range [0, 99].

題目意思很簡單,就是給你一棵樹,讓你判斷這棵樹全部節點的值是否是都是同一個數。input

直接遍歷節點,而後記錄下來再判斷就好。(其實能夠邊遍歷邊判斷)it

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int a[100];
public:

    void view(TreeNode* root) {
        if( root != NULL ) a[root->val] ++;
        if( root->right != NULL ) view(root->right);
        if( root->left != NULL ) view(root->left);
    }

    bool isUnivalTree(TreeNode* root) {
        memset(a, 0, sizeof(a));
        view(root);
        int cnt = 0;
        for(int i=0; i<100; i++) {
            if( a[i] != 0 ) cnt ++;
        }
        return cnt == 1;
    }
};
View Code

 

第二題:

967. Numbers With Same Consecutive Differences

Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K.io

Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid.event

You may return the answer in any order.

 

Example 1:

Input: N = 3, K = 7 Output: [181,292,707,818,929] Explanation: Note that 070 is not a valid number, because it has leading zeroes. 

Example 2:

Input: N = 2, K = 1 Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

 

Note:

  1. 1 <= N <= 9
  2. 0 <= K <= 9

 題目意思很簡單,看樣例基本能明白,給你一個長度n,和一個限定差值k,讓你找出全部長度爲n而且相鄰數位之間的差值等於k的這些數(任何順序),除0以外不能有任何數是以0開頭。

有兩個坑點:

一、當N爲1的時候,0是正確的數。

二、當K爲0的時候,注意不要重複計算。

class Solution {
public:
    vector<int> numsSameConsecDiff(int N, int K) {
        vector<int> ans;
        if( N == 1 ) ans.push_back(0);
        for(int i=1; i<10; i++) {
            queue<int> q;
            q.push(i);
            int len = N-1;
            while( len!=0 ) {
                int si = q.size();
                while( si -- ) {
                    int st = q.front(); q.pop();
                    int last = st % 10;
                    if( last + K < 10 ) q.push(st*10+last+K);
                    if( last - K >= 0 && (last+K != last-K) ) q.push(st*10+(last-K));
                }
                len --;
            }
            while( !q.empty() ) {
                int top = q.front();
                ans.push_back(top);
                q.pop();
            }
        }
        return ans;
    }
};
點擊查看代碼
相關文章
相關標籤/搜索