【问题标题】:check if first array is sorted and if there are consecutive duplicate elements check second array at the index of duplicate elements检查第一个数组是否已排序以及是否有连续的重复元素检查重复元素索引处的第二个数组
【发布时间】:2020-10-23 14:36:14
【问题描述】:

我们需要检查第一个数组是否已排序,如果有连续重复元素,则检查第二个数组在重复元素的索引处。 This is my code and output

由于a[2]=a[3],我期望的输出是假的,因此我们应该移动到第二个数组并在那里b[2]>b[3]

例如: 1.

array1[]={1,2,3,4,5};
array2[]={5,6,4,3,2};

这应该返回 true 因为第一个数组已排序

2.

array1[]={1,2,3,3,4};
array2[]={5,4,3,6,2};

这也应该返回 true 因为 array1[2]=array1[3] 然后我们去 array2 那里 array2[2],因此它应该返回 true

3.

array1[]={1,2,3,3,4};
array2[]={5,4,4,4,2};

这也应该返回 true 因为 array1[2]=array1[3] 然后我们去 array2 那里 array2[2]=array2[3],因此它应该返回 true

4.

array1[]={1,2,3,3,4};
array2[]={5,6,4,3,2};

这也应该返回 false 因为 array1[2]=array1[3] 然后我们去 array2 那里 array2[2]>array2[3],因此它应该返回 false

【问题讨论】:

  • case 4) 它返回 true,因为在您的代码中有 if (a [i] < a[i+1]) return true,并且在 array1 (1
  • 我该如何解决这个@ibra
  • 正如我之前所说:您必须将代码分成两部分。 1)检查第一个数组是否已排序,stackoverflow.com/a/19458302/3429103 中有一个很好的解释,2)您的代码连续完成相同值的验证并检查第二个数组。祝你好运。

标签: java arrays


【解决方案1】:

在您的情况 (4) 中,它返回 true,因为在您的代码中,您有 if (a [i] < a[i+1]) return true 在循环内检查重复值。所以在 array1 (1

类似

public class Main
{
    public static boolean isSorted(int[] a) 
    {
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i] > a[i + 1]) 
            {
                return false;
            }
        }

        return true;
    }
    
    public static boolean checkDuplicate(int[] a, int b[]) 
    {
        for (int i = 0; i < a.length - 1; i++) 
        {
            if (a[i] == a[i + 1] && b[i] > b[i + 1]) 
            {
                return false;
            }
        }

        return true;
    }
    
    public static void main(String[] args) 
    { 
        int array1[]={1,2,3,3,4}; 
        int array2[]={5,6,4,3,2};
        
        if(isSorted(array1) && checkDuplicate(array1,array2))
            System.out.println("True");
        else
            System.out.println("False");
    }
}

【讨论】:

  • 感谢帮助
猜你喜欢
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 2021-12-14
  • 2011-11-14
  • 2021-03-11
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多