ltx_zero

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Num 203 移除链表元素

题是对链表的基本操作,判断的时候需要考虑到,head处删除,只有一个元素需要或者不需要删除,没有元素,这几种容易引发边界错误

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode*temp=new ListNode(0);
        ListNode*pre=new ListNode(0);
        if(head==NULL) return head;
        while(head->val==val && head->next!=NULL)
            head=head->next;
        while(head!=NULL && head->val==val)
            head=head->next;
        if(head==NULL) return head;
        pre=head;
        temp=head->next;
        if(temp==NULL) return head;
        while(temp->next!=NULL)
        {
            if(temp->val==val)   
            {
                pre->next=temp->next;
                temp=temp->next;
            }
            else
            {
                pre=pre->next;
                temp=temp->next;
            }
        }
        if(temp->val==val)
            pre->next=NULL;
        return head;
    }
};
View Code

 Num 198 打家劫舍

最基础的dp问题,每一个就是当前的加减二或者直接用减一

不要理所让然的认为不可能有空输入

另外基础dp问题还不是很熟练

class Solution {
public:
    int rob(vector<int>& nums) {
        int len=nums.size();
        if(len==0) return 0;
        if(len==1) return nums[0];
        if(len==2) return max(nums[0],nums[1]);
        vector<int>dp;
        dp.push_back(nums[0]);
        dp.push_back(max(nums[0],nums[1]));
        for(int i=3;i<=len;i++)
            dp.push_back(max(dp[i-2],dp[i-3]+nums[i-1]));
        return dp[len-1];
    }
};
View Code

 

posted on 2019-07-09 22:22  ltx_zero  阅读(114)  评论(0编辑  收藏  举报