LeetCode 20191125

1.在排序数组中查找元素的第一个和最后一个位置
按我的理解 我认为是没有问题的
做法就是 遍历数组然后设置计数,如果碰到目标值就计数
然后 int end 为当前下标
这样只要用末尾下标和长度即可以得到首位下标咯

我的实现如下:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int length;
        int end=-1;
        int begin=-1;
        vector<int>none;
        none.push_back(-1);
        none.push_back(-1);
        if(nums.size()==0){return none;}
        for(int i=0;i<nums.size();i++){
            if(nums[i]==target){
                length++;
                end=i;
            }
        }
        if(end==-1){return none; }
        else{
             begin =end-length+1;
        }
        vector<int>res;
        res.push_back(begin);
        res.push_back(end);
        return res;
    }
};

网上的代码多是使用复杂的二分法 私以为不需要那么麻烦

2.删除链表中的重复节点

自解√

这道题主要因为是已经排序的链表,判断是否相等然后排列链子就可以了,方法:设置当前链和下一个,如果相等就移动下一个,直到与当前cur不相等,然后接链,
要注意的是,在最后一个不同链值的时候,因为下一个为空,所以需要特定考虑,然后另当前链的指向为空,终结掉这个链表

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head==NULL){
            return NULL;
        }
        ListNode* cur=head;
        ListNode* Next=head->next;
        ListNode* res=new ListNode(0);
        res->next=cur;
        while(cur!=NULL&&Next!=NULL){
            
            if(cur->val==Next->val){
                Next=Next->next;
            }
            else{
                cur->next=Next;
                cur=Next;
                Next=cur->next;
            }
            if(Next==NULL){cur->next=NULL;}
        }
        return res->next;
    }
};

注意1:判断当前链表非空时 是判断整个链表非空 不是只对val

发布了44 篇原创文章 · 获赞 9 · 访问量 3351

猜你喜欢

转载自blog.csdn.net/puying1/article/details/103246286
今日推荐