目录
算法解释
指针与常量
修饰变量
//没有区别
const int p = 12; //p不能被修改
p = 42; //编译出错
int const q = 42; //q不能被修改
q = 12; //编译出错
修饰指针
const int a = 12;
const int b = 42;
const int c = 54;
const int *r = &a; //*r不能被修改
*r= b; //编译出错
int* const p = &b; //p不能被修改
p = &c; //编译出错
int const *q = &c; //*q不能被修改
*q = a; //编译出错
指针函数与函数指针
//指针函数,一个返回类型是指针的函数
int* addition(int a , int b)
{
int* sum = new int(a+b);
return sum;
}
int subtraction(int a,int b)
{
return a-b;
}
int operation(int x,int y,int (*func)(int,int))
{
return (*func)(x,y);
}
//minus是函数指针,指向函数的指针
int (*minus)(int,int) = subtraction;
int* m = addition(1,2);
int n = operation(3,*m,minus);
Two Sum
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0,right = numbers.size() - 1;
int sum = 0;
while(left < right)
{
sum = numbers[left] + numbers[right];
if(sum > target) right--;
else if (sum < target) left++;
else {
return vector<int> {left+1,right+1};
}
}
return vector<int>{-1,-1};
}
};
归并两个有序数组
比较两个数组,将较大的一直往后放
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = nums1.size() - 1;
m--;
n--;
while(n >= 0)
{
while(m>=0 && nums1[m] > nums2[n])
{
swap(nums1[i--],nums1[m--]);
}
swap(nums1[i--],nums2[n--]);
}
}
};
快慢指针
双指针fast--slow
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast!=nullptr && fast->next!=nullptr)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
ListNode* p1 = head;
ListNode* p2 = fast;
while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
}
return NULL;
}
};