LeetCode 面試題57 - II(劍指offer) 和爲s的連續正數序列

今天畢業五年了,一直忙於工作和享受,自從當年找完工作後就一直沒有再刷過題,作爲搬磚的碼農,覺得還是應該養成長期刷題的習慣堅持下去。之前堅持了每天被一會單詞,如今雅思一本也快看完了,從今天開始準備在保證每週一題的最低基礎上堅持下去,不爲別的,主要是想多動腦,刷個幾十年堅持下去,應該可以預防老年癡呆。。。

題目:

 滑動窗口的解法:注意蛋疼的int[][]返回值類型,十分蛋疼

public class Solution
{
    public int[][] FindContinuousSequence(int target)
    {
        List<int[]> res = new List<int[]>();
        int leftIndex = 1;
        int rightIndex = 2;
        int loopNum = target/2 + 1;
        target *= 2; 
        while(rightIndex <= loopNum)
        {
            int sum = (leftIndex + rightIndex) * (rightIndex - leftIndex + 1);
            if(sum < target)
            {
                rightIndex++;
            }
            else if(sum > target)
            {
                leftIndex++;
            }
            else
            {
                List<int> seq = new List<int>();
                for(int i = 0; i < rightIndex - leftIndex + 1; i++)
                {
                    seq.Add(leftIndex + i);
                }
                res.Add(seq.ToArray());
                leftIndex++;
                rightIndex = leftIndex + 1;
            }        
        }
        return res.ToArray();
    }
}

另外數學的求根法: https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/solution/xiang-jie-hua-dong-chuang-kou-fa-qiu-gen-fa-jian-g/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章