var search = function(nums, target) {
let l = 0
let r = nums.length - 1
let mid
while(l <= r){
mid = Math.floor( (l+r)/2 )
if(nums[mid] === target) return mid
else if(nums[mid] < target){
l = mid + 1
}else{
r = mid - 1
}
}
return -1
};
方法一:使用两层for循环,外层寻找等于val的数组元素,内层通过覆盖来达到“删除”这个元素,时间复杂度为On^2
方法二:一层for循环 + 快慢指针 ,时间复杂度为On
- 一层 for 循环用快指针 fastIndex 遍历数组元素
- 快指针用来寻找下一个不等于 val 的元素
- 找到之后赋值给慢指针的位置,慢指针后移
var removeElement = function(nums, val) {
let slowIndex = 0
for(let fastIndex = 0; fastIndex < nums.length; fastIndex ++){
if(nums[fastIndex] !== val){
nums[slowIndex] = nums[fastIndex]
slowIndex ++
}
}
return slowIndex
};
由于数组元素中有负数,所有可以使用双指针
- i从数组下标0开始,j从末尾开始
- arr为长度与nums相同,存放元素平方后的结果
var sortedSquares = function(nums) {
let i = 0
let j = nums.length - 1
let k = nums.length - 1
let arr = new Array(nums.length)
while(i <= j){
if(nums[i]*nums[i] > nums[j]*nums[j]){
arr[k--] = nums[i]*nums[i]
i ++
}else{
arr[k--] = nums[j]*nums[j]
j --
}
}
return arr
};
var minSubArrayLen = function(target, nums) {
let sum = 0
let ans = 100001
let j = 0
for(let i = 0; i < nums.length; i++){
sum += nums[i]
while( sum >= target){
let l = i - j + 1
ans = Math.min(ans, l)
sum -= nums[j]
j ++
}
}
if(ans === 100001) return 0
return ans
};
var totalFruit = function(fruits) {
if(fruits.length <= 1) return fruits.length
fruits.push(-1)
let set = new Set()
let i = 0
let ans = -1
for(let j = 0; j < fruits.length; j++){
if(set.size === 2 && !set.has(fruits[j])){
let len = j - i
ans = Math.max(ans, len)
set.forEach((val) => {
if(val !== fruits[j-1]){
set.delete(val)
}
})
set.add(fruits[j])
i = j - 1
while(fruits[i] === fruits[j - 1]){
i --
}
i ++
}else{
if(!set.has(fruits[j]) && fruits[j] != -1){
set.add(fruits[j])
}
}
}
if(set.size === 1) return fruits.length - 1
return ans
};
var generateMatrix = function(n) {
let arr = []
for(let i = 0; i < n; i++){
arr.push(new Array(n))
}
let next = [[0,1], [1,0], [0,-1], [-1,0]]
let flag = 0
let k = 1
let x = 0
let y = 0
let nx = 0
let ny = 0
while(k <= n*n){
x = nx
y = ny
arr[x][y] = k
nx = x + next[flag][0]
ny = y + next[flag][1]
if( nx<0 || nx >= n || ny < 0 || ny >= n || arr[nx][ny] ){
flag = (flag + 1) % 4
nx = x + next[flag][0]
ny = y + next[flag][1]
}
k ++
}
return arr
};
|