代碼隨想錄leetcode200題之額外題目

目錄

  • 1 介紹
  • 2 訓練
  • 3 參考

1 介紹

本博客用來記錄代碼隨想錄leetcode200題之額外題目相關題目。

2 訓練

題目1:1365. 有多少小于當前數字的數字

解題思路:二分查找。

C++代碼如下,

class Solution {
public:vector<int> smallerNumbersThanCurrent(vector<int>& a) {vector<int> b = a;sort(b.begin(), b.end());vector<int> res;for (auto x : a) {auto iter = lower_bound(b.begin(), b.end(), x);int i = distance(b.begin(), iter);res.emplace_back(i);}return res;}
};

python3代碼如下,

class Solution:def smallerNumbersThanCurrent(self, a: List[int]) -> List[int]:b = copy.deepcopy(a)b.sort()res = []for x in a:i = bisect.bisect_left(b, x)res.append(i)return res 

題目2:941. 有效的山脈數組

解題思路:模擬。

C++代碼如下,

class Solution {
public:bool validMountainArray(vector<int>& a) {int n = a.size();if (n < 3) return false;if (!(a[0] < a[1])) return false;if (!(a[n-2] > a[n-1])) return false;int i = 0;while (i+1 < n && a[i] < a[i+1]) i += 1;int j = i;while (j+1 < n && a[j] > a[j+1]) j += 1;if (j != n-1) return false;return true;}
};

python3代碼如下,

class Solution:def validMountainArray(self, a: List[int]) -> bool:n = len(a)if n < 3:return False if not (a[0] < a[1]):return Falseif not (a[-2] > a[-1]):return False i = 0 while i + 1 < n and a[i] < a[i+1]:i += 1 j = i while j + 1 < n and a[j] > a[j+1]:j += 1 if j != n-1:return False return True 

題目3:1207. 獨一無二的出現次數

解題思路:模擬。

C++代碼如下,

class Solution {
public:bool uniqueOccurrences(vector<int>& a) {unordered_map<int, int> cnt1;for (auto x : a) cnt1[x]++;unordered_map<int, int> cnt2;for (auto [k, v] : cnt1) {cnt2[v]++;if (cnt2[v] > 1) return false;}return true;}
};

python3代碼如下,

class Solution:def uniqueOccurrences(self, a: List[int]) -> bool:cnt = collections.Counter(a)res = collections.Counter(cnt.values())for k in res:if res[k] > 1:return False return True 

題目4:283. 移動零

解題思路:雙指針。

C++代碼如下,

class Solution {
public:void moveZeroes(vector<int>& a) {int n = a.size();int i = 0;int j = 0;while (j < n) {if (a[j] != 0) {swap(a[i], a[j]);i += 1;}j += 1;}return;}
};

python3代碼如下,

class Solution:def moveZeroes(self, a: List[int]) -> None:"""Do not return anything, modify nums in-place instead."""n = len(a)i = 0j = 0 while j < n:if a[j] == 0:pass else:a[i], a[j] = a[j], a[i]i += 1j += 1return 

題目5:189. 輪轉數組

解題思路:分三步走。第1步,先翻轉整個列表。第2步,翻轉列表的[0,k)部分。第3步,翻轉列表的[k,n)部分。

C++代碼如下,

class Solution {
public:void rotate(vector<int>& a, int k) {int n = a.size();k %= n;reverse(a.begin(), a.end());reverse(a.begin(), a.begin()+k);reverse(a.begin()+k, a.end());return;}
};

python3代碼如下,

class Solution:def reverse(self, a: list, i: int, j: int) -> None:while i < j:a[i], a[j] = a[j], a[i]i += 1 j -= 1 return def rotate(self, a: List[int], k: int) -> None:"""Do not return anything, modify nums in-place instead."""n = len(a)k %= n self.reverse(a, 0, n-1)self.reverse(a, 0, k-1)self.reverse(a, k, n-1)return 

題目6:724. 尋找數組的中心下標

解題思路:模擬。

C++代碼如下,

class Solution {
public:int pivotIndex(vector<int>& a) {a.insert(a.begin(), 0);int n = a.size();vector<int> s(n, 0);for (int i = 1; i < n; ++i) {s[i] = s[i-1] + a[i];}for (int i = 1; i < n; ++i) {if (s[i-1] == s[n-1] - s[i]) {return i-1;}}return -1;}
};

python3代碼如下,

class Solution:def pivotIndex(self, a: List[int]) -> int:a.insert(0, 0)n = len(a)s = [0] * n for i in range(1,n):s[i] = s[i-1] + a[i] for i in range(1,n):if s[i-1] == s[n-1] - s[i]:return i-1 return -1        

題目7:34. 在排序數組中查找元素的第一個和最后一個位置

解題思路:二分查找。

C++代碼如下,

class Solution {
public:vector<int> searchRange(vector<int>& a, int target) {int n = a.size();auto iter = lower_bound(a.begin(), a.end(), target);if (iter == a.end() || *iter != target) {return {-1,-1};}int i = distance(a.begin(), iter);iter = upper_bound(a.begin(), a.end(), target);int j = distance(a.begin(), iter);j -= 1;return {i,j};}
};

python3代碼如下,

class Solution:def searchRange(self, nums: List[int], target: int) -> List[int]:i = bisect.bisect_left(nums, target)if i >= len(nums) or (i < len(nums) and nums[i] != target): #特判return [-1,-1]j = bisect.bisect_right(nums, target)j -= 1return [i,j]

題目8:922. 按奇偶排序數組 II

解題思路:雙指針算法。

C++代碼如下,

class Solution {
public:vector<int> sortArrayByParityII(vector<int>& a) {int n = a.size();int i = 0, j = 1;while (i < n && j < n) {while (i < n && a[i] % 2 == 0) {i += 2;}while (j < n && a[j] % 2 == 1) {j += 2;}if (i < n && j < n) {swap(a[i], a[j]);}}return a;}
};

python3代碼如下,

class Solution:def sortArrayByParityII(self, a: List[int]) -> List[int]:n = len(a)i = 0j = 1while i < n and j < n:while i < n and a[i] % 2 == 0:i += 2 while j < n and a[j] % 2 == 1:j += 2 if i < n and j < n:a[i], a[j] = a[j], a[i]return a 

題目9:35. 搜索插入位置

解題思路:二分查找。

C++代碼如下,

class Solution {
public:int searchInsert(vector<int>& nums, int target) {auto iter = lower_bound(nums.begin(), nums.end(), target);return distance(nums.begin(), iter);}
};

python3代碼如下,

class Solution:def searchInsert(self, nums: List[int], target: int) -> int:return bisect.bisect_left(nums, target)

題目10:24. 兩兩交換鏈表中的節點

解題思路:對于node->a->b->…,三步操作。第1步,a.next = b.next。第2步,b.next = a。第3步,node.next = b。

C++代碼如下,

/*** 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) {ListNode *dummy = new ListNode(0, head);ListNode *node = dummy;while (node->next != nullptr && node->next->next != nullptr) {ListNode *a = node->next;ListNode *b = node->next->next;a->next = b->next;b->next = a;node->next = b;node = node->next->next;}return dummy->next;}
};

python3代碼如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:dummy = ListNode(0,head)node = dummy while node.next is not None and node.next.next is not None:a = node.nextb = node.next.next a.next = b.next b.next = a node.next = b node = node.next.next return dummy.next 

題目11:234. 回文鏈表

解題思路:將原鏈表拆分成2個鏈表(先切割后翻轉鏈表)。比較這2個鏈表中的元素值。

C++代碼如下,

/*** 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* reverse(ListNode* head) {ListNode *a = head;ListNode *prev = nullptr;while (a != nullptr) {ListNode *b = a->next;a->next = prev;prev = a;a = b;}return prev;}bool isPalindrome(ListNode* head) {ListNode *slow = head;ListNode *fast = head;while (slow->next != nullptr && fast->next != nullptr && fast->next->next != nullptr) {slow = slow->next;fast = fast->next->next;}//切割ListNode *a = head;ListNode *b = slow->next;slow->next = nullptr;//翻轉b = reverse(b);while (a != nullptr && b != nullptr) {if (a->val != b->val) {return false;}a = a->next;b = b->next;}return true;}
};

python3代碼如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverse(self, head: Optional[ListNode]) -> Optional[ListNode]:a = head prev = None while a is not None:b = a.next a.next = prev prev = a a = breturn prev def isPalindrome(self, head: Optional[ListNode]) -> bool:slow = head fast = head while slow.next is not None and fast.next is not None and fast.next.next is not None:slow = slow.next fast = fast.next.next a = head b = slow.next slow.next = None#翻轉鏈表bb = self.reverse(b) while a is not None and b is not None:if a.val != b.val:return False a = a.next b = b.next return True 

題目12:143. 重排鏈表

解題思路:先通過快慢指針分割原鏈表為ab。然后翻轉鏈表b。最后合并兩個鏈表即可。

C++代碼如下,


python3代碼如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def reverse(self, head: Optional[ListNode]) -> Optional[ListNode]:prev = None a = head while a is not None:b = a.next a.next = prev prev = a a = breturn prev def reorderList(self, head: Optional[ListNode]) -> None:"""Do not return anything, modify head in-place instead."""fast = head slow = head while slow.next is not None and fast.next is not None and fast.next.next is not None:slow = slow.next fast = fast.next.next #先分隔a = head b = slow.next #后翻轉b = self.reverse(b)slow.next = None res = a prev = None while a is not None and b is not None:na = a.next nb = b.next if prev is not None:prev.next = a             a.next = bprev = b a = na b = nb if a is not None and prev is not None:prev.next = a return res 

3 參考

代碼隨想錄

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/41107.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/41107.shtml
英文地址,請注明出處:http://en.pswp.cn/web/41107.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

卷積神經網絡(CNN)和循環神經網絡(RNN) 的區別與聯系

卷積神經網絡&#xff08;CNN&#xff09;和循環神經網絡&#xff08;RNN&#xff09;是兩種廣泛應用于深度學習的神經網絡架構&#xff0c;它們在設計理念和應用領域上有顯著區別&#xff0c;但也存在一些聯系。 ### 卷積神經網絡&#xff08;CNN&#xff09; #### 主要特點…

解決C++編譯時的產生的skipping incompatible xxx 錯誤

問題 我在編譯項目時&#xff0c;產生了一個 /usr/bin/ld: skipping incompatible ../../xxx/ when searching for -lxxx 的編譯錯誤&#xff0c;如下圖所示&#xff1a; 解決方法 由圖中的錯誤可知&#xff0c;在編譯時&#xff0c;是能夠在我們指定目錄下的 *.so 動態庫的…

python函數和c的區別有哪些

Python有很多內置函數&#xff08;build in function&#xff09;&#xff0c;不需要寫頭文件&#xff0c;Python還有很多強大的模塊&#xff0c;需要時導入便可。C語言在這一點上遠不及Python&#xff0c;大多時候都需要自己手動實現。 C語言中的函數&#xff0c;有著嚴格的順…

Java基礎(六)——繼承

個人簡介 &#x1f440;個人主頁&#xff1a; 前端雜貨鋪 ?開源項目&#xff1a; rich-vue3 &#xff08;基于 Vue3 TS Pinia Element Plus Spring全家桶 MySQL&#xff09; &#x1f64b;?♂?學習方向&#xff1a; 主攻前端方向&#xff0c;正逐漸往全干發展 &#x1…

【Web】

1、配倉庫 [rootlocalhost yum.repos.d]# vi rpm.repo ##本地倉庫標準寫法 [baseos] namemiaoshubaseos baseurl/mnt/BaseOS gpgcheck0 [appstream] namemiaoshuappstream baseurlfile:///mnt/AppStream gpgcheck0 2、掛載 [rootlocalhost ~]mount /dev/sr0 /mnt mount: /m…

QT操作各類數據庫用法詳解

文章目錄 創建內存SQLITE數據庫QSqlTableModel操作數據庫表連接國產數據庫多線程數據處理不指定數據庫名打開數據庫QT對各種數據庫的支持情況處理數據庫表名QT連接各種數據庫Qt提供了一個名為QtSQL模塊的強大組件, 使得在Qt應用程序中連接和操作多種類型的數據庫變得相對簡單。…

Vulnhub-Os-hackNos-1(包含靶機獲取不了IP地址)

https://download.vulnhub.com/hacknos/Os-hackNos-1.ova #靶機下載地址 題目&#xff1a;要找到兩個flag user.txt root.txt 文件打開 改為NAT vuln-hub-OS-HACKNOS-1靶機檢測不到IP地址 重啟靶機 按住shift 按下鍵盤字母"E"鍵 將圖中ro修改成…

Github 2024-07-06 開源項目日報 Top10

根據Github Trendings的統計,今日(2024-07-06統計)共有10個項目上榜。根據開發語言中項目的數量,匯總情況如下: 開發語言項目數量Python項目3TypeScript項目2Rust項目2非開發語言項目1C++項目1QML項目1MDX項目1JavaScript項目1Assembly項目1免費編程書籍和學習資源清單 創建…

JS 四舍五入使用整理

一、Number.toFixed() 把數字轉換為字符串,結果的小數點后有指定位數的數字,重點返回的數據類型為字符串 toFixed() 方法將一個浮點數轉換為指定小數位數的字符串表示,如果小數位數高于數字,則使用 0 來填充。 toFixed() 方法可把 Number 四舍五入為指定小數位數的數字。…

Vue 3集成krpano 全景圖展示

Vue 3集成krpano 全景圖展示 星光云全景系統源碼 VR全景體驗地址 星光云全景VR系統 將全景krpano靜態資源文件vtour放入vue項目中 導入vue之前需要自己制作一個全景圖 需要借助官方工具進行制作 工具下載地址&#xff1a;krpano工具下載地址 注意事項&#xff1a;vuecli…

Hook 實現 Windows 系統熱鍵屏蔽(二)

目錄 前言 一、介紹用戶賬戶控制&#xff08;UAC&#xff09; 1.1 什么是 UAC &#xff1f; 2.2 UAC 運行機制的概述 2.3 分析 UAC 提權參數 二、 NdrAsyncServerCall 函數的分析 2.1 函數聲明的解析 2.2 對 Winlogon 的逆向 2.3 對 rpcrt4 的靜態分析 2.4 對 rpcrt4…

YOLOv8_obb數據集可視化[旋轉目標檢測實踐篇]

先貼代碼,周末再補充解析。 這個篇章主要是對標注好的標簽進行可視化,雖然比較簡單,但是可以從可視化代碼中學習到YOLOv8是如何對標簽進行解析的。 import cv2 import numpy as np import os import randomdef read_obb_labels(label_file_path):with open(label_file_path,…

探索 IPython 的環境感知能力:詳解 %env 命令的妙用

探索 IPython 的環境感知能力&#xff1a;詳解 %env 命令的妙用 在數據科學和編程的海洋中&#xff0c;環境變量扮演著至關重要的角色。IPython&#xff0c;這一強大的交互式計算工具&#xff0c;通過其內置的魔術命令 %env&#xff0c;為我們提供了與環境變量交互的強大能力。…

git基礎指令總結持續更新之git分支簡介和基本操作,解決合并和沖突,回退和rebase(變基),分支命名和分支管理,學習筆記分享

git 分支簡介和基本操作 Git 分支是 Git 的核心特性之一&#xff0c;它允許開發者在不同的開發線上工作&#xff0c;而不會影響主代碼庫。以下是 Git 分支的簡介和一些基本操作&#xff1a; 分支的概念&#xff1a; 分支是 Git 中的一個獨立開發線。創建分支時&#xff0c;G…

rtt設備驅動框架學習——內核對象基類object

內核對象基類object 這個基類是內核所有對象的基類 在rt-thread/include/rtdef.h文件里有對內核對象基類object的定義 /*** Base structure of Kernel object*/ struct rt_object {char name[RT_NAME_MAX]; /**< name of kernel object */rt…

清新簡約之美,開源個人博客:Jekyll Theme Chirpy

Jekyll Theme Chirpy&#xff1a;簡約不簡單&#xff0c;Chirpy 讓你的博客煥發新意- 精選真開源&#xff0c;釋放新價值。 概覽 Jekyll Theme Chirpy 是為Jekyll靜態網站生成器設計的現代主題&#xff0c;以其清新、簡約的設計風格和用戶友好的交互體驗受到開發者和博客作者的…

為企業知識庫選模型?全球AI大模型知識庫RAG場景基準測試排名

大語言模型常見基準測試 大家對于AI模型理解和推理能力的的基準測試一定非常熟悉了&#xff0c;比如MMLU&#xff08;大規模多任務語言理解&#xff09;、GPQA&#xff08;研究生級別知識問答&#xff09;、GSMSK&#xff08;研究生數學知識考察&#xff09;、MATH&#xff08…

Zabbix監控軟件

目錄 一、什么是Zabbix 二、zabbix監控原理 三、zabbix 安裝步驟 一、什么是Zabbix ●zabbix 是一個基于 Web 界面的提供分布式系統監視以及網絡監視功能的企業級的開源解決方案。 ●zabbix 能監視各種網絡參數&#xff0c;保證服務器系統的安全運營&#xff1b;并提供靈活的…

python讀取寫入txt文本文件

讀取 txt 文件 def read_txt_file(file_path):"""讀取文本文件的內容:param file_path: 文本文件的路徑:return: 文件內容"""try:with open(file_path, r, encodingutf-8) as file:content file.read()return contentexcept FileNotFoundError…

Swagger的原理及應用詳解(十)

本系列文章簡介&#xff1a; 在當今快速發展的軟件開發領域&#xff0c;特別是隨著微服務架構和前后端分離開發模式的普及&#xff0c;API&#xff08;Application Programming Interface&#xff0c;應用程序編程接口&#xff09;的設計與管理變得愈發重要。一個清晰、準確且易…