🧸🧸🧸各位大佬大家好,我是猪皮兄弟🧸🧸🧸
废话不多说,直接来做题!!
一、📖链表的奇偶重排(中等)
思路:这道题要求的不是数值的奇偶,要求的是点位奇偶,那么用一个计数器就搞定了,创建两个新的头,分别存奇偶就ok
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* oddEvenList(ListNode* head) {
// write code here
if(head==nullptr||head->next==nullptr)
return head;
ListNode* even = new ListNode(0);
ListNode*eventail=even;
ListNode* odd = new ListNode(0);
ListNode*oddtail=odd;
ListNode*cur=head;
int count=1;
while(cur)
{
if(count%2!=0)
{
eventail->next=cur;
eventail=eventail->next;
}
if(count %2==0)
{
oddtail->next=cur;
oddtail=oddtail->next;
}
count++;
cur=cur->next;
}
eventail->next=odd->next;
oddtail->next=nullptr;
delete odd;
head=even->next;
delete even ;
return head;
}
};
二、📖删除有序链表中重复的元素(中等)
nowcoder删除有序链表中重复的元素
进阶要求时间复杂度O(N),空间复杂度O(1),那么就只能遍历链表了,不然的话可以用辅助数组来存储
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(head==nullptr||head->next==nullptr)
return head;
ListNode*newhead=new ListNode(0);
newhead->next=head;
ListNode*prev=newhead,*cur=head;
while(cur&&cur->next)
{
if(cur->val!=cur->next->val)
{
prev=cur;
cur=cur->next;
}
else
{
while(cur->next!=nullptr&&cur->val==cur->next->val)
{
cur=cur->next;
}
cur=cur->next;
prev->next=cur;
if(prev==newhead)
head=cur;
}
}
delete newhead;
return head;
}
};
三、📖二分查找-Ⅰ
int search(vector<int>& nums, int target) {
// write code here
int left=0;
int right=nums.size()-1;
while(left<=right)
{
int mid=left+(right-left)/2;
if(nums[mid]<target)
{
left=mid+1;
}
else if(nums[mid]>target)
{
right=mid-1;
}
else
{
return mid;
}
}
return -1;
}
};
四、📖二维数组中的查找(中等)
nowcoder二维数组中的查找
暴力求解的话时间复杂度O(N*M)要求时间复杂度O(N+M),来看看下面的线性搜索方法吧
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
if(array.size()==0)
return false;
int r=array.size();
int c=array[0].size();
int row=r-1;
int col=0;
while(row>=0&&col<=c-1)
{
int tmp=array[row][col];
if(tmp<target)
{
col++;
}
else if(tmp>target)
{
row--;
}
else
return true;
}
return false;
}
};
}
五、📖寻找峰值
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型
*/
int findPeakElement(vector<int>& nums) {
// write code here
if(nums.size()==1)
return 0;
for(int i=0;i<nums.size();i++)
{
if(i==0&&nums[1]<nums[0])
return 0;
else if(i==nums.size()-1&&nums[nums.size()-1]>nums[nums.size()-2])
return nums.size()-1;
else if(nums[i]>nums[i-1]&&nums[i]>nums[i+1])
{
return i;
}
}
return 0;
}
};
六 、📖牛客oj总结
牛客网是个很不错的刷题软件,也希望大家能天天在上面刷刷题,大厂offer指日可待啊兄弟们。刷起来。