美文网首页
leetcode-day6

leetcode-day6

作者: 爆炸的热水袋 | 来源:发表于2019-05-25 20:05 被阅读0次

    输入值是指针考虑是不是NULL, next是不是NULL
    输入值是数组考虑长度为0


    Search a 2D Matrix II

    Instead of beginning with matrix[0][0], begin with left bottom or right up - > then when greater or less, the direction is only.

    Swap Nide in Pairs

    ListNode* swapPairs(ListNode* head) {
        if(head==NULL) return NULL;
        if(head->next==NULL) return head;
        ListNode* newhead = head->next;
        while(head!=NULL&&head->next!=NULL){
            ListNode* second = head->next;
            ListNode* first = head;
            head = second->next;
            if(second->next==NULL||second->next->next==NULL) first->next = second->next;
            else first->next = second->next->next;
            second->next = first;
        }
        return newhead;
    }
    

    Pay attenion to where first->next should be point to, not simple second->next or second->next->next as well as the condition in while.

    
        
        ListNode* swapPairs(ListNode* head) {
            if(head==NULL) return NULL;
            if(head->next==NULL) return head;
            ListNode* newhead = head->next;
            head->next = swapPairs(head->next->next);
            newhead->next = head;
            return newhead;
        }
    

    Container With Most Water

    int maxArea(vector<int>& height) {
        int left = 0;
        int right = height.size()-1;
        int max = 0;
        while(left<right){
            if(height[left]<height[right]){
                int area = height[left]*(right - left);
                if(max<area) max = area;
                left++;
            }
            else{
                int area = height[right]*(right - left);
                if(max<area) max = area;
                right--;
                
            }
        }
        return max;
    }
    

    Use two pointer is fine, but need to consider the circumstance that even current boundary has greater area then adjancent one, there may be much higher height in middle, so still need to search to center.

    相关文章

      网友评论

          本文标题:leetcode-day6

          本文链接:https://www.haomeiwen.com/subject/cqugzqtx.html