翻转链表
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
while (curr != NULL) {
struct ListNode* nextTemp = curr->next;//nextTemp的作用是为了记录,以便再反转后可以
curr->next = prev; // //找到下一个结点
prev = curr;
curr = nextTemp;
}
return prev;
}
struct ListNode* midfind(struct ListNode* head) { //用快慢指针找中间节点
struct ListNode* slow = head;
struct ListNode* fast = head;
while (fast->next!= NULL && fast->next->next != NULL) { // 修改了循环条件
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
struct ListNode* reverseList(struct ListNode* head) { //翻转链表
struct ListNode* pre = NULL;
struct ListNode* cur = head;
while (cur != NULL) {
struct ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
struct ListNode* mergeList(struct ListNode* l1, struct ListNode* l2) { //合并链表
struct ListNode dummy;
struct ListNode* tail = &dummy;
while (l1 != NULL && l2 != NULL) {
tail->next = l1;
l1 = l1->next;
tail = tail->next;
tail->next = l2;
l2 = l2->next;
tail = tail->next;
}
if (l1 != NULL) {
tail->next = l1;
} else {
tail->next = l2;
}
return dummy.next;
}
void reorderList(struct ListNode* head) {
if (head == NULL)
return;
struct ListNode* mid = midfind(head);
struct ListNode* l1 = head;
struct ListNode* l2 = mid->next;
mid->next = NULL;
l2 = reverseList(l2);
head = mergeList(l1, l2); // 修改了函数返回的用法
}
//暴力求解(时间超限)
int minSubArrayLen(int s, int* nums, int numsSize) {
if (numsSize == 0) {
return 0;
}
int ans = INT_MAX;
for (int i = 0; i < numsSize; i++) {
int sum = 0;
for (int j = i; j < numsSize; j++) {
sum += nums[j];
if (sum >= s) {
ans = fmin(ans, j - i + 1);
break;
}
}
}
return ans == INT_MAX ? 0 : ans;
}
//滑动窗口
int minSubArrayLen(int target, int* nums, int numsSize) {
int result=INT_MAX;
int ans=0;int sum=0;int i=0;
for(int j=0;j<numsSize;j++)
{
sum+=nums[j];
while(sum>=target)
{
ans=j-i+1;
result=fmin(result,ans);
sum=sum-nums[i];
i++;
}
}
return result==INT_MAX?0:result;
}
滑动窗口讲解视频参考:【拿下滑动窗口! | LeetCode 209 长度最小的子数组-哔哩哔哩】 https://b23.tv/q4YearN