简单的模拟题,合并区间
class Solution {
public:
string convertIntToStr(int num)
{
char str[255];
sprintf(str, "%d", num);
return str;
}</p>
<pre><code>vector&lt;string&gt; summaryRanges(vector&lt;int&……
将一个正整数,转换成二进制,然后颠倒顺序,再输出成十进制。模拟题。
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
//To binary
vector<int> nums(32, 0);
int index = 0;
while(n > 0)
{
nums[index++] = n % 2;
……
判断一个数n是否是happy number。happy number的定义是,各位数依次平方求和,看是否能等于1,如果不等于1,再重复上述过程。实际上,这个过程将会是一个循环。[猜的,并没有证明]。
class Solution {
public:
map<int, bool>flag;
bool isHappy(int n)
{
if (n == 1)
{
……
判断一个数是否是2的幂。有的是位运算,移位即可。
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0)
{
return false;
}
while(true)
{
if (n == 1) {
return true;
}
if (n % 2 != ……
判断一个数是否是丑数,模拟解出来的。
class Solution {
public:
bool isUgly(int num) {
if (num <= 0)
{
return false;
}
while(true)
{
if(num%2 == 0)
{
num /= 2;
}
else if(num%3 ……
模拟一个栈,用vector偷懒解决问题。
class Stack {
public:
vector<int> stack;
// Push element x onto stack.
void push(int x) {
stack.push_back(x);
}</p>
<pre><code>// Removes the element on top of the stack.
void pop() {
stack.pop_back();……
这个题挺有意思的,给定一个排序的数组:1,2,3,4,5,6,7,但是这个数组经过了一个旋转,比如,4,5,6,7,1,2,3。这个时候求这个数组中最小的元素。O(n)一定能解出来。记得去年面试滴滴打车的时候问过类似的问题。当时笃定是二分查找,但是感觉说得不清楚。这次做题显然思路就清晰了。
class Solution {
public:
void bi……
判断两个字符串是否含有相同的字母且字母个数相同。
class Solution {
public:
bool isAnagram(string s, string t) {
vector<int> sCount(26, 0);
for (int i = 0;i < s.length();i++)
{
sCount[s[i] - 'a']++;
}
for (int i = 0;i < t.length();……
求出给定数组中,超过半数的元素(保证有数字超过半数)。注意数组长度的奇偶。hash记录一下即可。
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int> m_nums;
m_nums.clear();
for (int i = 0;i < nums.size(……
判断给定数组中是否含有重复元素。hash表即可解。实际上我用的是map,即C++中的二叉搜索树。O(logn)的解法,时间不是特别好。
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
map<int, bool> m_nums;
m_nums.clear();
for (in……