写一个判断算法

新手上路,请多包涵

一个list对象有种多个对象
1.如果对象num都是“01”,则返回“01”
2.如果对象num都是“03”,则返回“03”
3.如果对象num有“01”或“03”,则返回“05”
4.如果对象num只要有“02,则返回“02”

阅读 2.4k
3 个回答

双重for去重复,然后再判断

直接统计个数:
遍历,统计num每种情况出现的次数,得到结果:

{
    "01": 10,
    "02": 5,
    "03": 8,
    ...
}

然后对结果进行判断:

  1. 02次数 > 0, 返回 "02"
  2. 01次数 == list.size(),返回"01"
  3. 03次数 == list.size(),返回"03"
  4. 返回"05"

扣一点的话:

boolean hasOne = false, hasThree = false;
for (String item : list) {
    if ("02".equals(item)) return "02";
    if ((hasThree && "01".equals(item))
        || (hasOne && "03".equals(item))
    )
        return "05";
    if (!hasOne && "01".equals(item)) hasOne = true;
    if (!hasThree && "03".equals(item)) hasThree = true;
}
return hasOne ? "01" : "03";

原答案:

if (list.contains("02")) return "02";
if (list.contains("01")) return list.contains("03") ? "05" : "01"
else return "03";
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题