haveThree

Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.
haveThree([3, 1, 3, 1, 3]) → true
haveThree([3, 1, 3, 3]) → false
haveThree([3, 4, 3, 3, 4]) → false

Solution1:

public boolean haveThree(int[] nums) {
  boolean lastIs3 = false;
  int count = 0;
  for(int i=0; i<nums.length; i++ ) {
    if(nums[i]==3 ) {
      if(lastIs3) {
        return false;
      }
      lastIs3 = true;
      count++;
    } else {
      lastIs3 = false;
    }
  }
  if(count == 3) {
    return true;
  }
  return false;
}

Solution2:

public boolean haveThree(int[] nums) {
  String num = Arrays.toString(nums);
  if(!num.contains("3, 3") && count3(nums) == 3 ){
    return true;
  }
  return false;
}
public int count3 (int[] nums) {
  int count = 0;
  for (int val:nums) {
    if(val == 3) {
      count++;
    }
  }
  return count;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,984评论 0 23
  • 读书的勇气 其实,这么多年一直认为自己停学习的,可是,今天才真到,真的没有。有的还是后悔,自己真的是不知不觉的浪费...
    真真卒迹阅读 86评论 0 0
  • 文|成悦 -01- 佛说:一沙一世界,一尘一劫,仿佛我们每一次重逢和离别,如同三生石上刺破手指滴落的血。千里暗香拂...
    与君成悦阅读 1,737评论 17 37
  • 窗外的雨越下越大,一对小鸟落在窗外的护栏上叽叽喳喳叫个不停,我蹑手蹑脚走过去,小鸟停止了叫声,四只小圆眼睛惊恐的望...
    华丽的回眸一笑_阅读 485评论 10 14
  • 我有一个粗心的主人,我把他弄丢了。 外面下着雨,我躲在屋檐下,看着人来人往,很无助。 我叫可可,在上周的某一个清晨...
    hello张小凡阅读 2,141评论 0 2