目录
704. 二分查找
35.搜索插入位置
34. 在排序数组中查找元素的第一个和最后一个位置
27. 移除元素
977.有序数组的平方
209.长度最小的子数组
59.螺旋矩阵II
704. 二分查找
704. 二分查找 - 力扣(LeetCode)
class Solution {
public:
int search(vector& nums, int target) {
int left = 0,right = nums.size()-1;
while (left<=right)
{
int mid = left+(right-left)/2;
if (nums[mid]==target)return mid;
else if(nums[mid]>target) right = mid-1;
else left = mid+1;
}
return -1;
}
};
35.搜索插入位置
35. 搜索插入位置 - 力扣(LeetCode)
class Solution {
public:
int searchInsert(vector& nums, int target) {
int left = 0,right = nums.size()-1;
while (left<=right)
{
int mid = left+(right-left)/2;
if (nums[mid]==target)return mid;
else if(nums[mid]>target)right = mid-1;
else left = mid+1;
}
return left;
}
};
34. 在排序数组中查找元素的第一个和最后一个位置
34. 在排序数组中查找元素的第一个和最后一个位置 - 力扣(LeetCode)
class Solution {
public:
vector searchRange(vector& nums, int target) {
int rightBorder = getRightBorder(nums,target);
if(rightBorder==-1||nums[rightBorder]!=target) return {-1,-1};
int leftBorder = getLeftBorder(nums,target);
return {leftBorder,rightBorder};
}
private:
int getRightBorder(vector&nums, int target){
int left = 0,right = nums.size()-1;
int rightBorder = -1;
while (left<=right)
{
int mid = left+(right-left)/2;
if (nums[mid]>target)right = mid-1;
else
{
rightBorder = mid;
left = mid+1;
}
}
return rightBorder;
}
int getLeftBorder(vector&nums, int target){
int left = 0,right = nums.size()-1;
int leftBorder = -1;
while (left<=right)
{
int mid = left+(right-left)/2;
if (nums[mid]
27. 移除元素
27. 移除元素 - 力扣(LeetCode)
class Solution {
public:
int removeElement(vector& nums, int val) {
int k = 0;
for(int ii=0;ii
977.有序数组的平方
977. 有序数组的平方 - 力扣(LeetCode)
class Solution {
public:
vector sortedSquares(vector& nums) {
int left =0,right = nums.size()-1;
vector ans(nums.size(),0);
int i = right;
while(left<=right)
{
if (nums[left]+nums[right]<0)
{
ans[i--] = nums[left]*nums[left++];
}
else ans[i--] = nums[right]*nums[right--];
}
return ans;
}
};
209.长度最小的子数组
209. 长度最小的子数组 - 力扣(LeetCode)
class Solution {
public:
int minSubArrayLen(int target, vector& nums) {
int left = 0,right = 0,len = nums.size();
int ans =INT_MAX ,amount = 0;
while(right=target)
{
if(right-left+1
59.螺旋矩阵II
59. 螺旋矩阵 II - 力扣(LeetCode)
class Solution {
public:
vector> generateMatrix(int n) {
int k = 0;
int tmp = 1;
vector>ans(n,vector(n,0));
while(tmp<=n*n)
{
for(int jj=k;jj<=n-1-k;jj++)
{
ans[k][jj] = tmp++;
}
for (int ii = k+1;ii=k;jj--)
{
ans[n-1-k][jj] = tmp++;
}
for (int ii = n-k-2;ii>k;ii--)
{
ans[ii][k] = tmp++;
}
k++;
}
if (n%2==1)
{
ans[k-1][k-1]=n*n;
}
return ans;
}
};