java - Java 中的数组 - Core Java

标签 java arrays

在这个问题中 如果对于数组中的每一对相邻元素,至少有一个是该值,则值在数组中“无处不在”。如果给定值在数组中无处不在,则返回 true。

isEverywhere({1, 2, 1, 3}, 1) → true,因为 1 存在于 (1,2) 和 (1,3) 中 isEverywhere({1, 2, 1, 3}, 2) → false,因为 2 在 (1,2) 但不在 (1,3) 中 isEverywhere({1, 2, 1, 3, 4}, 1) → false,因为 1 出现在 2 对 (1,2) 和 (1,3) 中,但 4 没有一对 1

我的部分工作代码如下,你能帮我解决这个问题吗,卡了好久。

::代码::

public boolean isEverywhere(int[] nums, int val) {    
    boolean flag = false;    
    for(int i=0;i<nums.length;i++){    
      for(int j=i+2;j<nums.length;j++){    
            if(nums[i] == nums[j]){    
                 flag = true;    
            }    
      }    
    }      
  return flag;     
}         

预期结果:

                           `Expected` `This` `Run`       

isEverywhere({1, 2, 1, 3}, 1) → true true OK
isEverywhere({1, 2, 1, 3}, 2) → false true X
isEverywhere({1, 2, 1, 3, 4}, 1) → 假真 X

最佳答案

试试这个:

boolean isEverywhere(int[] nums, int val) {    

        // use i+=2 to get start index of pair.
        for(int i=0;i<nums.length;i+=2) {

                // other index in the pair.
                int j = i + 1;

                // make sure the other index really exists.
                if(j < nums.length) { 

                        // if it exists..and val is not equal to 
                        // either in the pair..return false.
                        if(nums[i] != val && nums[j] != val) {
                                return false;
                        }       
                } else {
                        // no pair..one element case.
                        // return true if that element is val..else return false.
                        return nums[i] == val; 
                }       
        }

        // array has no unpaired element..and all pairs have val.
        return true;     
}    

关于java - Java 中的数组 - Core Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4502849/

相关文章:

java - 如何在 XML 文件中构建多维数组?

java - netty ChannelInboundHandlerAdapter将帧切成约1500个字节

java - 如何求最大质数、除 1 以外的最小因数、数之和

Java Swing - 一个窗口中的多个控件集

c++ - 如何以正确的方式将结构数组参数传递给函数?

php - 在编写查询时需要帮助

java - FlowScope 在页面刷新时变得清晰

java - 使用 Rest Assured 从 JSON API 获取唯一属性

python - 在 numpy 数组中找到一段 Trues

javascript - For循环遍历数组并创建彼此为 sibling 的div