365天挑战LeetCode1000题——Day 069 两两交换链表中的节点 设计链表 数组中两元素的最大乘积

24. 两两交换链表中的节点

在这里插入图片描述

代码实现(自解)

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* swapPairs(ListNode* head) {if (!head) return nullptr;if (!head->next) return head;ListNode* left = head, *mid = head->next, *right;left->next = mid->next;mid->next = left;head = mid;while (left->next && left->next->next) {mid = left->next;right = mid->next;left->next = right;mid->next = right->next;right->next = mid;left = mid;}return head;}
};

707. 设计链表

在这里插入图片描述

代码实现(自解)

class MyLinkedList {
private:ListNode* head;int size;
public:MyLinkedList() {head = new ListNode();size = 0;}int get(int index) {if (index >= size) return -1;ListNode* tmp = head->next;while (index--) {tmp = tmp->next;}return tmp->val;}void addAtHead(int val) {ListNode* tmp = new ListNode(val);tmp->next = head->next;head->next = tmp;size++;}void addAtTail(int val) {ListNode* tmp = head;while (tmp->next) tmp =tmp->next;tmp->next = new ListNode(val);size++;}void addAtIndex(int index, int val) {if (index < 0) {addAtHead(val);return;}ListNode* tmp = head;while (index-- && tmp) tmp = tmp->next;if (!tmp) return;ListNode* tmp1 = new ListNode(val);tmp1->next = tmp->next;tmp->next = tmp1;size++;}void deleteAtIndex(int index) {if (index < 0 || index >= size) return;ListNode* tmp = head;while (index--) tmp = tmp->next; ListNode* tmp1 = tmp->next;tmp->next =tmp1->next;delete(tmp1);size--;       }
};/*** Your MyLinkedList object will be instantiated and called as such:* MyLinkedList* obj = new MyLinkedList();* int param_1 = obj->get(index);* obj->addAtHead(val);* obj->addAtTail(val);* obj->addAtIndex(index,val);* obj->deleteAtIndex(index);*/

1464. 数组中两元素的最大乘积

在这里插入图片描述

代码实现(自解)

class Solution {
public:int maxProduct(vector<int>& nums) {int first = min(nums[0], nums[1]), second = max(nums[0], nums[1]);for (int i = 2; i < nums.size(); i++) {if (nums[i] > second) {first = second;second = nums[i];}else if (nums[i] > first) first = nums[i];}return (first - 1) * (second - 1);}
};


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部