Day1-Array01
Concept
- Time Complexity: The Time Complexity of an algorithm/code is not equal to the actual time required to execute a particular code, but the number of times a statement executes
- Space Complexity: The total amount of extra memory space used by an algorithm/program, excluding the input and output
Note
- If n is 10^5, need take the algorithm time complexity like O(nlogn)
- If n is 100 or 1000, could use brute force, like O(n^2)
704. Binary Search
Note: there are two way, iterate and Recursive
Time Complexity && Space Complexity
Iterate
- Time Complexity: O(logn)
- If there are n element, the scope of every loop will be n, n/2, n/4, …n/2^k, k is the count of loop
- Finally, n/2^k >= 1, then n = 2^k, k = log2n, k is how many time the code be run
- Space Complexity: O(1)
- Since only create left/right one time
Recusive
- Time Complexity: O(logn)
- depth of recusive is logn
- Space Complexity: O(logn)
- depth of recusive(logn) * space need for every recusive
Iterate: left include, right include, [left, right]
1 | var search = function(nums, target) { |
Iterate: left include, right exclude, [left, right)
1 | var search = function (nums, target) { |
Recursive
- Three steps in Recsive
- define function parameter and return
- end condition
- logical for every recusive
1 | var search = function(nums, target) { |
27. Remove Element
Note
- use slow pointer and fast pointer is a smart solution
Time Complexity && Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
Slow pointer and fast pointer
1 | // fast pointer will find the non-target first |
Two pointer, 0 and nums.length-1
- Need consider more case to pass all test
- For the while inside while, need check whether break the outside while condition
- After while, nums[right] == val or !== are two cases
1 | var removeElement = function (nums, val) { |
- Title: Day1-Array01
- Author: Guoyi
- Created at : 2024-08-15 17:16:41
- Updated at : 2024-12-07 03:58:41
- Link: https://guoyiwang.github.io/Algorithm/Day1-Array01/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments