classSolution { public: ListNode* reverseKGroup(ListNode* head, int k){ ListNode* result = newListNode(0); result->next = head; ListNode* pre = result; while (head) { ListNode* tail = pre; for (int i = 0; i < k; ++i) { tail = tail->next; if (tail == nullptr) return result->next; } ListNode* next = tail->next; tie(head, tail) = Reverse(head, tail); pre->next = head; tail->next = next; head = tail->next; pre = tail; } return result->next; } pair<ListNode*, ListNode*> Reverse(ListNode* head, ListNode* tail) { ListNode* pre = nullptr; ListNode* cur = head; while (pre != tail) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return {tail, head}; } };
三:缺失的第一个正数
1. 哈希表
想要记录没有出现的数据,通常使用哈希表,这里无法使用额外空间,我们可以对数组进行原地操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intfirstMissingPositive(vector<int>& nums){ int len = nums.size(); for (auto& num: nums) if (num <= 0) num = INT_MAX; for (auto& num: nums) { int temp = abs(num); if (temp <= len) nums[temp - 1] = -abs(nums[temp - 1]); // 这里可能修改后面的数据,所以取负值 } for (int i = 0; i < len; ++i) if (nums[i] > 0) return i + 1; return len + 1; } };
2. 置换
我们可以尝试把元素的值与数组索引对应
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intfirstMissingPositive(vector<int>& nums){ int len = nums.size(); for (int i = 0; i < len; ++i) while (nums[i] > 0 && nums[i] <= len && nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]); for (int i = 0; i < len; ++i) if (nums[i] != i + 1) return i + 1; return len + 1; } };