每日5题(3)
(1)删除链表中的重复元素
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* head) {
auto t=new ListNode(-1);
t->next=head;
auto p=t;
while(p->next){
auto q=p->next;
while(q&&p->next->val==q->val){
q=q->next;
}
if(p->next->next==q){
p=p->next;
}else{
p->next=q;
}
}
return t->next;
}
};
(2)https://tianchi.aliyun.com/oj/73486278997090424/102293175780184758
描述
返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K 。
如果没有和至少为 K 的非空子数组,返回 -1 。
- 1≤A.length≤50000
- −105≤A[i]≤105
- 1≤K≤109
class Solution {
public:
/**
* @param A: the array
* @param K: sum
* @return: the length
*/
int shortestSubarray(vector<int> &A, int K) {
// Write your code here.
bool flag=false;
int sum[A.size()+10];
int minval=100000;
for(int i=0;i<A.size();i++){
sum[i+1]=sum[i]+A[i];
}
for(int i=0;i<=A.size();i++){
for(int j=i;j<=A.size();j++){
int res=sum[j]-sum[i];
if(res>=K){
int leng=j-i;
if(leng<minval){
minval=leng;
flag=true;
}
}
}
}
if(flag){
return minval;
}else{
return -1;
}
}
};
(3)反向迭代器
所有的容器都有迭代器,vector<int> ::iterator it=vec.begin()
vector<int>::iterator it=vec.begin()
for(vector<int>::iterator it=vec.begin();it!=vec.end();it++){
}
//方向迭代器
for(vector<int>::iterator it=vec.rbegin();it!=vec.rend();it++){
}
从尾到头打印链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int>res;
while(head){
res.push_back(head->val);
head=head->next;
}
return vector<int>(res.rbegin(),res.rend());
}
};
(4)输出链表倒数第k个元素
//输出链表倒数第k个元素,两次遍历链表,不需要对链表进行存储
ListNode * findKthToTail(ListNode * pListHead, int k){
int n = 0;
for (auto p = pListHead; p; p = p->next){
n++;
}
if (n < k){ return NULL; }
for (int i = 0; i < n - k; i++){
p = p->next;
}
return p;
}
(5)还需要进一步理解 数组中出现次数超过一般的数字
数组中有一个数字超过数组个数的一半,找出这个数字
注:超过数组个数的一半,即该数字出现的次数超过其它所有数字出现次数的和。
(1)设置2个变量分别保存出现的次数,和当前比较出现次数比较多的元素
(2)如果后面比较的元素等于该数,则出现次数+1,否则-1
(3)对于次数=0,则更新参与比较的元素,和次数置为1
class Solution {
public:
int moreThanHalfNum_Solution(vector<int>& nums) {
int count=1;
int val=nums[0];
for(int i=1;i<nums.size();i++){
if(nums[i]==val){
count++;
}else{
count--;
}
if(count==0){
val=nums[i];
count=1;
}
}
return val;
}
};
(6)复杂链表的复制
//复杂链表的复制
class Solution{
public :
ListNode * copyrandomList(ListNode * head){
for (auto p = head; p;){
auto np = new ListNode(p->val);
auto tmp = p->next;
p->next = np;
np->next = tmp;
p = tmp;
}
for (auto p = head; p; p = p->next->next){
if (p->random){
p->next->random = p->random->next;
}
}
auto dummy = new ListNode(-1);
auto cur = dummy;
auto q = head;//恢复原链表
for (auto p = head; p; p = p->next){
cur->next = p->next;
cur = cur->next;
p = p->next;
q->next = cur->next;//q->next=p->next;也可以
q = q->next;
}
return dummy->next;
}
};

浙公网安备 33010602011771号