ltx_zero

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

Num 141 环形链表

题很简单,注意空指针特判一定要head==NULL在前面,不然head->next可能直接报错

这个题没用到pos,有点神奇。

哈希表可能是更好的方法,过两天认真研究一下。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if( head==NULL||head->next==NULL) return false;
        ListNode*fast=new ListNode(0);
        ListNode*slow=new ListNode(0);
        fast=head->next->next;
        slow=head->next;
        while(fast!=NULL)
        {
            if(fast==slow) return true;
            slow=slow->next;
            fast=fast->next;
            if(fast==NULL) return false;//注意已经是原来的next了就不要再next了
            fast=fast->next;
        }
        return false;
    }
};
View Code

 看ArrayList

 Num 167 两数之和||-输入有序数组

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> two(2);
        int index1=1;
        int index2=2;
        for(int i=1;i<=numbers.size();i++)
        {
            index1=i;index2=i+1;
            while(numbers[index1-1]+numbers[index2-1]<target && index2<numbers.size())
            {
                index2++;
            }
            if 
                (numbers[index1-1]+numbers[index2-1]!=target) continue;
            else
            {
                two[0]=index1;
                two[1]=index2;
                break;
            }
        }
        return two;
    }
};
View Code

开始用最笨的遍历做的,emm空间使用还行,时间就很长,显然不是标准答案

ps:二分超时了,可能是我的二分太笨了。。。。

 哈希仍然是一种办法

更快的办法是双指针,其实刚开始想到了,但是没想清楚他的正确性,争取慢慢来!

注意vector<int>two(2);

定义的时候给好大小,或者老老实实使用push_back

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int index1=1;
        int index2=numbers.size();
        while(numbers[index1-1]+numbers[index2-1]!=target)
        {
            if(numbers[index1-1]+numbers[index2-1]>target)
                index2--;
            else 
                index1++;
        }
        vector<int>two(2);
        two[0]=index1;
        two[1]=index2;
        return two;
    }
};
View Code

 事实上从百分之60以上,方法就是一样的了,中途省略重复的加法或者判定条件都可以提高效率

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int index1=1;
        int index2=numbers.size();
        while(index1<index2)
        {
            int sum=numbers[index1-1]+numbers[index2-1];//省略了while和if的反复计算,或者index1和index0先不减一最后一起,都会提高效果,实际方法一样
            if(sum==target)
                break;
            else if(sum>target)  
                index2--;
            else 
                index1++;
        }
        vector<int>two(2);
        two[0]=index1;
        two[1]=index2;
        return two;
    }
};
View Code

 

posted on 2019-07-08 19:39  ltx_zero  阅读(149)  评论(0编辑  收藏  举报