核心考点:二进制计算
解题思路:
这道题比较简单,但我们这里介绍一种位运算法,可以减少无效操作。
把一个整数减去1之后再和原来的整数做与运算,得到的结果相当于把整数的二进制表示中最右边的1变成0。
class Solution {
public:
int NumberOf1(int n) { //从右开始 逐位归零
int count = 0;
while(n){
n &= (n - 1);
count++;
}
return count;
}
};
核心考点:链表,前后指针的使用,边界条件检测
解题思路:
我们使用快慢指针的方法,由于我们要找到倒数第k个节点,我们发现,当快指针先走K步,再和慢指针一起走,当走到空的时候正好慢指针走到倒数第k个节点。
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead == nullptr)
{
return nullptr;
}
ListNode* front=pListHead;
ListNode* cur=pListHead;
while(k>0 && front)
{
k--;
front=front->next;
}
while(front)
{
front=front->next;
cur=cur->next;
}
return cur;
}
};
核心考点:栈和队列的实用
解题思路:
由于这里我们用的是c语言,所以要自己创建栈的实现,我们遍历给定的字符串 。当我们遇到一个左括号时,我们会期望在后续的遍历中,有一个相同类型的右括号将其闭合。由于后遇到的左括号要先闭合,因此我们可以将这个左括号放入栈顶当我们遇到一个右括号时,我们需要将一个相同类型的左括号闭合。此时,我们可以取出栈顶的左括号并判断它们是否是相同类型的括号。如果不是相同的类型,或者栈中并没有左括号,那么字符串无效,返回 False。。
bool isValid(char* s) {
Stack st;
StackInit(&st);
bool match = true;
while (*s)
{
if (*s == '[' || *s == '(' || *s == '{')
{
StackPush(&st, *s);
++s;
}
else
{
if (StackEmpty(&st))
{
match = false;
break;
}
char ch = StackTop(&st);
StackPop(&st);
if ((*s == ']' && ch != '[')
|| (*s == '}' && ch != '{')
|| (*s == ')' && ch != '('))
{
match = false;
break;
}
else
{
++s;
}
}
}
if (match == true)
{
match = StackEmpty(&st);
}
StackDestroy(&st);
return match;
}