思路
其实题目的示例解释已经很明确了,只要遍历数组每个元素:
{
c
a
n
d
i
e
s
[
i
]
+
e
x
t
r
a
C
a
n
d
i
e
s
>
=
m
a
x
(
c
a
n
d
i
e
s
[
]
)
返回true
c
a
n
d
i
e
s
[
i
]
+
e
x
t
r
a
C
a
n
d
i
e
s
<
m
a
x
(
c
a
n
d
i
e
s
[
]
)
返回false
\begin{cases} candies[i]+extraCandies>=max(candies[]) &\text{返回true}\\ candies[i]+extraCandies<max(candies[]) &\text{返回false}\\ \end{cases}
{candies[i]+extraCandies>=max(candies[])candies[i]+extraCandies<max(candies[])返回true返回false
代码
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies){
List<Boolean> list = new ArrayList<Boolean>();
int length = candies.length;
int flag=0; //最大值标志位(数组下标值)
for(int i=1;i<length;i++) {
if(candies[i]>candies[flag]) flag=i;
}
for(int i=0;i<length;i++) {
if(candies[i]+extraCandies>=candies[flag])
list.add(true);
else list.add(false);
}
return list;
}
}
- 时间复杂度O(n),空间复杂度O(1)
- 初始化
List<Boolean> list = null
时,执行list.add()
会出错,改成List<Boolean> list = new ArrayList<Boolean>();
就对了,这是为什么呢?——官方文档List<E>
是接口,有许多子类,若要初始化,必须指明实现的哪个类。 - 评论区找最大值有别的写法,可以注意一下:
for (int candy : candies) {
max=Math.max(max , candy);
}