已经正式在实习了,很久都没有刷题了(应该有半年了吧),感受仍是不能把思惟锻炼落下,因此决定每周末刷一次LeetCode。node
这是第一周(菜的真实,只作了两题,还有半小时不想看了,冷~)。git
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, 100]
.[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; } };
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 <= N <= 9
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; } };