两个 flag

Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo([4, 2, 2, 3]) → true
twoTwo([2, 2, 4]) → true
twoTwo([2, 2, 4, 2]) → false

Solution:

public boolean twoTwo(int[] nums) {
  boolean first2 = false;
  boolean lastIs2 = false;
  for(int val : nums) {
    if(val == 2) {
      if (lastIs2 == false && first2 == false ) {
        first2 = true;
      } else {
        first2 = false;
      }
      lastIs2 = true;
    } else {
      if(first2 == true) {
        return false;
      }
      lastIs2 = false;
    }
  }

  if(lastIs2 && first2) {
    return false;
  }

  return true;
  
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,496评论 0 23
  • edenmandom 伊甸真男之職業心得 餐飲經營業務環節多,隨意性強,手工操作比重大,所以管理的難度也大,稍有不...
    黑貓子阅读 3,523评论 0 1
  • 1. 我没有跑过马拉松。 但我的朋友里有人跑过,金子是其中一位。 在毕业前的喝酒聊天中,金子告诉我:“滕哥,我觉得...
    滕训阅读 3,192评论 0 1
  • “老妈,我觉得老爸好陌生啊,他都没怎么管过我!”练完琴的女儿一边收拾,一边对娟子嘟哝。 爸爸好陌生?明明天天生...
    happystone阅读 2,761评论 0 1

友情链接更多精彩内容