455. Assign Cookies

C++

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
    sort(g.begin(),g.end());
    sort(s.begin(),s.end());
    int glength=g.size();
    int result=0;
    int count=0;
    int i=0;
    while(count<glength&&i<s.size())
    {
        for(;i<s.size();i++)
        {
            if(s[i]>=g[count]&&count<glength)
            {
                result++;
                count++;
            }
        }
    }
    return result;
    }
};

Java

public class Solution {
    public int findContentChildren(int[] g, int[] s) {
    Arrays.sort(g);
    Arrays.sort(s);
    int glength=g.length;
    int result=0;
    int count=0;
    int i=0;
    while(count<glength&&i<s.length)
    {
        for(;i<s.length;i++)
        {
            if(count<glength&&s[i]>=g[count])
            {
                result++;
                count++;
            }
        }
    }
    return result;
    }
}

Javascript

/**
 * @param {number[]} g
 * @param {number[]} s
 * @return {number}
 */
var findContentChildren = function(g, s) {
    g.sort(function(a,b){return a-b;});
    s.sort(function(a,b){return a-b;});
    var glength=g.length;
    var result=0;
    var count=0;
    var i=0;
    while(count<glength&&i<s.length)
    {
        for(;i<s.length;i++)
        {
            if(s[i]>=g[count])
            {
                result++;
                count++;
            }
        }
    }
    return result;
};

此處思路都是一樣的,但是在各自語言下代碼有些許差別,值得一提的是

C++中判斷條件為 if(s[i]>=g[count]&&count<glength)

Java中判斷條件為  if(count<glength&&s[i]>=g[count])

Javascript中判斷條件為   if(s[i]>=g[count])

Javascript中當(dāng)count大于數(shù)組g的長度后,g[count]=undefined,s[i]>undefined為false
C++中當(dāng)count大于數(shù)組g的長度后,此處為<vector> int g; g[count]=0,s[i]>0為true
Java中當(dāng)count大于數(shù)組g的長度后,會(huì)報(bào)錯(cuò)

最優(yōu)解

時(shí)間復(fù)雜度(nlogn)
Java

只有排序花費(fèi)了nlogn

我寫了兩個(gè)循環(huán)感覺多了,因?yàn)槲业诙€(gè)循環(huán)中的條件和第一個(gè)一樣,可以合并

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容