Leetcode解題思路

2021-10-05 05:36:15 字數 2235 閱讀 5215

所有簡單題的解題思路。

question: count the number of prime numbers less than a non-negative number,n

example:

input:

10output:

4explanation: there are 4 prime numbers less than 10

,there are 2,3

,5,7

時間複雜度小於 o

(n^2

)

對於如何判斷乙個數是否是質數,我們可以遍歷2到n-1,只要不出現整除即可判斷是質數。初步思路

int

countprimes

(int n)

// 判斷整數 n 是否是素數

bool

isprime

(int n)

優化**,我們可以對for (int i = 2; i < n; i++) 進行簡化, 判斷i * iint

countprimes

(int n)}}

int count =0;

for(

int i =

2; i

)return count;

}接下來我們看**展示:

來自 wikimedia

我們繼續優化**,我們發現對於2的倍數,2、4、6、8。4的倍數4、8、16。會發現有重複出現。

我們可以修改一下j,讓j從i的平方開始遍歷。這樣就可以優化相應的時間。最後**如下

int
countprimes

(int n)}}

int count =0;

for(

int i =

2; i

)return count;

}question:invert a binary tree

example:

input:

4
/ \

27/ \ / \13

69output:

4

/ \

72/ \ / \96

31

遞迴反轉二叉樹,經典**:

void

helper

(treenode * root)

treenode*

inverttree

(treenode* root)

**question:**給乙個二叉搜尋樹,找出所給q,p對應值的最近公共父母。

example:

6

/ \

28/ \ / \04

79/ \ 3

5input: root =[6

,2,8

,0,4

,7,9

,null,null,3,

5], p =

2, q =

8output:

6explanation: the lca of nodes 2

and8 is 6.

answer:遞迴演算法,利用二叉搜尋樹的性質,左邊小,右邊大。當p,q的值在某個節點分叉時,則當前節點就是最近公共節點。例如2,8.在6節點分叉。再如2,4在2節點分叉。故遞迴滿足條件

1、p,q的值乙個大於當前值乙個小於當前值,返回當前節點

2、如果都小於當前值,則往左子樹走,如果都大於則往右子樹走。

**如下:

treenode*

lowestcommonancestor

(treenode* root, treenode* p, treenode* q)

leetcode 95 96 解題思路

95.unique binary search trees ii given an integer n,generate all structurally uniquebst s binary search trees that store values 1 n.example input 3out...

leetcode 160解題思路

題意 求兩個單向鍊錶的交點。要求時間複雜度為o n 空間複雜度為o 1 答案如下 include include using namespace std definition for singly linked list.struct listnode 方法一 unordered map,時間複雜度...

leetcode 287解題思路

題意 1,n 範圍內的n 1個數,有且僅有乙個數字重複,請找出這個重複的數字,解題思路有以下三種方法 include include include using namespace std 方法一 改變陣列值 可能與題目要求不符 取相反數,判斷該數是否是重複數,非常簡單的方法 class solut...