-3
私のプログラムには、配列内の要素を検索してそのインデックスを返すメソッドがあります。何らかの理由で、配列がソートされていなかった場合と同じようにインデックスを返しています。ここでプログラムはソートされたインデックスを返していますが、配列は決してソートされませんでした
はメソッドです:
public static ArrayList elementIndex(int search) {
ArrayList<Integer> index = new ArrayList<Integer>();
for (int i = 0; i<array.length; i++)
if (search == array[i]) {
index.add(i + 1);
}
return index;
}
私は場合には、それが何か持っていることが含まれますので、私は配列をソートだけの時間が従来の方法にあった:中
public static int mostCommon(int size) {
int[] arraySorted = array;
int mostCommon = 0, mostCommonCount = 0, currentCount = 0;
Arrays.sort(arraySorted);
for (int i = 1; i < size; i++) {
if (arraySorted[i - 1] == arraySorted[i]) {
currentCount++;
if (currentCount > mostCommonCount) {
mostCommonCount = currentCount;
mostCommon = arraySorted[i];
}
}
else
currentCount = 0;
}
return mostCommon;
}
'Arrays.sort()'は変更方法です。適用される配列を永続的に変更します。以前に配列をソートした場合は、プログラムの後半でソートされたままになります。 –
'int [] arraySorted = Arrays.copyOf(array、array.length);' – 4castle
を使ってコピーを作成するだけです。なぜ「i + 1」に+1がありますか?私はそれが 'index.add(i)' –