1.Hamming Distance
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
python
bin() 返回一个整数 int 或者长整数 long int 的二进制表示,返回字符串。
str.count(sub, start= 0,end=len(string)) 该方法返回子字符串在字符串中出现的次数。
sub – 搜索的子字符串
start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
2.Merge Two Binary Trees
class Solution(object):
def mergeTrees(self, t1, t2):
if t1 and t2:
root = TreeNode(t1.val + t2.val)
root.left = self.mergeTrees(t1.left, t2.left)
root.right = self.mergeTrees(t1.right, t2.right)
return root
else:
return t1 or t2
and x and y 布尔”与” - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 (a and b) 返回 20。
or x or y 布尔”或” - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。
not not x 布尔”非” - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False
python 中的and从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值。
or也是从左到有计算表达式,返回第一个为真的值。
3.Counting Bits
找规律,参见博客http://www.cnblogs.com/grandyang/p/5294255.html
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};
C++ vector:
vector<int> a ; //声明一个int型向量a
vector<int> a(10) ; //声明一个初始大小为10的向量
vector<int> a(10, 1) ; //声明一个初始大小为10且初始值
4.Island Perimeter
思路参见博客http://www.cnblogs.com/grandyang/p/6096138.html
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int res = 0, m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) continue;
res += 4;
if (i > 0 && grid[i - 1][j] == 1) res -= 2;
if (j > 0 && grid[i][j - 1] == 1) res -= 2;
}
}
return res;
}
};
要点:vector.empty()
5.Queue Reconstruction by Height
见博客http://www.cnblogs.com/grandyang/p/5928417.html
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
ans = []
for i in sorted(people, key=lambda x: (-x[0], x[1])):
ans.insert(i[1], i)
return ans
利用list.sort()参数key指定元素排序
>>> a.append(('a',1))
>>> a.append(('b',20))
>>>a.append(('c',-200))
>>> a.sort(key=lambda d:d[1],reverse=True)
>>> a
[('b', 20), ('a', 1), ('c', -200)]
list.insert(index, obj):
index – 对象 obj 需要插入的索引位置。
obj – 要插入列表中的对象。
C++解法:
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
sort(people.begin(), people.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.first > b.first || (a.first == b.first && a.second < b.second);});
vector<pair<int, int>> res;
for (auto a : people) {
res.insert(res.begin() + a.second, a);
}
return res;
}
};
C++ pair的用法:
http://blog.youkuaiyun.com/oceanlight/article/details/7890537
C++ sort:
sort(begin,end,compare)
bool compare(int a,int b)
{
return a<b; //升序排列,如果改为return a>b,则为降序
}
C++ auto:
自 C++ 11 以来,auto 关键字用于两种情况:声明变量时根据初始化表达式自动推断该变量的类型、声明函数时函数返回值的占位符。
auto f=3.14; //double
auto s("hello"); //const char*
auto z = new auto(9); // int*
auto x1 = 5, x2 = 5.0, x3='r';//错误,必须是初始化为同一类型
匿名函数:
http://www.cnblogs.com/lidabo/p/3908663.html
C++ for循环范围迭代:
int my_array[5] = {1, 2, 3, 4, 5};
// 每个数组元素乘于 2
for (int &x : my_array)
{
x *= 2;
cout << x << endl;
}
// auto 类型也是 C++11 新标准中的,用来自动获取变量的类型
for (auto &x : my_array) {
x *= 2;
cout << x << endl;
}
C++ vector.insert():
iterator insert( iterator loc, const TYPE &val );
void insert( iterator loc, size_type num, const TYPE &val );
void insert( iterator loc, input_iterator start, input_iterator end );
insert() 函数有以下三种用法:
在指定位置loc前插入值为val的元素,返回指向这个元素的迭代器,
在指定位置loc前插入num个值为val的元素
在指定位置loc前插入区间[start, end)的所有元素 .
举例:
//创建一个vector,置入字母表的前十个字符
vector <char> alphaVector;
for( int i=0; i < 10; i++ )
alphaVector.push_back( i + 65 );
//插入四个C到vector中
vector <char>::iterator theIterator = alphaVector.begin();
alphaVector.insert( theIterator, 4, 'C' );
//显示vector的内容
for( theIterator = alphaVector.begin(); theIterator != alphaVector.end(); theIterator++ )
cout < < *theIterator;
这段代码将显示:
CCCCABCDEFGHIJ
6.Palindromic Substrings
int countSubstrings(string s) {
int res = 0, n = s.length();
for(int i = 0; i < n; i++){
for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j]; j++)res++;
for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)res++;
}
return res;
}
见博客http://blog.youkuaiyun.com/huanghanqian/article/details/76577138
1)动态规划
2)遍历回文串中心
7.Single Number
1)xor(异或)满足交换律
2)任何数跟0异或等于它本身
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int i = 0; i < nums.size(); i++) {
ans ^= nums[i];
}
return ans;
}
};
8.Maximum Depth of Binary Tree
见博客http://www.cnblogs.com/grandyang/p/4051348.html
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
C++ max()
1)用递归进行深度优先搜索(DFS)
2)层序遍历二叉树(利用队列)
python or/and:
python 中的and从左到右计算表达式,若所有值均为真,则返回最后一个值,
若存在假,返回第一个假值。
or也是从左到有计算表达式,返回第一个为真的值。
>>'a'and'b'
'b'
>>''and'b'
''
>>'a'or'b'
'a'
>>''or'b'
'b'
9. Invert Binary Tree
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root) {
swap(root->left, root->right);
invertTree(root->right);
invertTree(root->left);
}
return root;
}
};
见博客:http://www.cnblogs.com/grandyang/p/4572877.html
1)递归
2)队列
idea:跟层序遍历相关的都可以用队列搞定
10.Find All Numbers Disappeared in an Array
见博客http://www.cnblogs.com/grandyang/p/6222149.html
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
for (int i = 0; i < nums.size(); ++i) {
int idx = abs(nums[i]) - 1;
nums[idx] = (nums[idx] > 0) ? -nums[idx] : nums[idx];
}
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0) {
res.push_back(i + 1);
}
}
return res;
}
};