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中當count大于數組g的長度后,g[count]=undefined,s[i]>undefined為false
C++中當count大于數組g的長度后,此處為<vector> int g; g[count]=0,s[i]>0為true
Java中當count大于數組g的長度后,會報錯
最優解
時間復雜度(nlogn)
Java
只有排序花費了nlogn
我寫了兩個循環感覺多了,因為我第二個循環中的條件和第一個一樣,可以合并