![](/img/trans.png)
[英]Given an array of integers as input, return true if the array is sorted. Note that the array can be sorted in either ascending or descending order
[英]Sorted array (ascending or descending) - true or false
這篇文章詳細介紹了如何確定數組的給定整數(升序或降序)是否已排序,返回代表該數組的 integer。 它還考慮了給定整數何時相等(例如,1 1 2 3 3 4 5)。
我一直在試圖弄清楚如何在 Main 中將返回值從 integer 更改為 boolean 值,但無濟於事。 意思是,如果數組按任意方向排序,則返回“true”,否則返回“false”。 現在已經在這兩天的大部分時間里一直在研究這個問題並且學到了很多東西,但我被困住了。 請幫忙。
我嘗試過 System.out.println(isSorted(array.toString("true"))); 看看這是否有效,但它沒有。
我嘗試將方法返回值從 int 切換為 boolean,然后將所有會受到影響的整數更改為“true”或“false”。
我嘗試將 Main 方法中的數組引用重新分配給字符串“true”或“false”。
import java.util.Scanner;
import java.util.Arrays;
class Sorted {
public static int isSorted(int[] intArray) {
boolean sortedAsc = true;
boolean sortedDesc = true;
boolean equalValues=true;
int result = 0;
for (int i = 0; i < intArray.length-1; i++)
{
equalValues = equalValues && (intArray[i] == intArray[i+1]);
sortedAscending = sortedAscending && ((intArray[i] <= intArray[i+1]));
sortedDescending = sortedDescending && ((intArray[i] >= intArray[i+1]));
if(sortedAsc) result= 1;
if(sortedDesc) result = -1;
if(equalValues) result = 2;
return result;
}
public static void main(String[] args) {
// TODO code application logic here
int array[] = new int[4];
array[0]=1;
array[1]=2;
array[2]=3;
array[3]=4;
int sortedResult = isSorted(array);
System.out.println( sortedResult == 1 || sortedResult == -1 || sortedResult == 2 );
}
}
如果我理解正確,您要做的是查看數組是否以升序或降序方式排序,或者數組中的所有元素是否相等(也按方式排序)。 如果是這種情況,我會將您的for
循環修改為:
for (int i = 0; i < intArray.length-1; i++)
{
equalValues = equalValues && (intArray[i] == intArray[i+1]);
sortedAscending = sortedAscending && ((intArray[i] <= intArray[i+1]));
sortedDescending = sortedDescending && ((intArray[i] >= intArray[i+1]));
}
基本上,您需要跟蹤布爾值的先前值以檢查排序的不變量。
如果您需要嚴格升序或嚴格降序,您只需將<=
更改為<
和>=
更改為>
現在為了根據result
打印你的結果為true
你只需要這樣做:
int sortedResult = isSorted(array)
System.out.println( sortedResult == 1 || sortedResult == -1 || sortedResult == 2 )
根據您對代碼的更新,您有一些錯誤,只需將方法isSorted
方法替換為以下方法並嘗試:
public static int isSorted(int[] intArray) {
boolean sortedAsc = true;
boolean sortedDesc = true;
boolean equalValues=true;
int result = 0;
for (int i = 0; i < intArray.length-1; i++)
{
equalValues = equalValues && (intArray[i] == intArray[i+1]);
sortedAsc = sortedAsc && ((intArray[i] <= intArray[i+1]));
sortedDesc = sortedDesc && ((intArray[i] >= intArray[i+1]));
}
if(sortedAsc) result= 1;
if(sortedDesc) result = -1;
if(equalValues) result = 2;
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.