配列aを並べ替えて、その要素の絶対値が何個の異なる値を共有することを求めます
3007 ワード
配列aを並べ替えて、その要素の絶対値を求めて何個の異なる値がありますか?
考え方:
2つのindexは、0に最も近い2つの要素から2端に遍歴し、毎回2つのindexが存在する要素の絶対値を比較し、小さい値を取り、最後の1回の値と比較し、大きい場合はcount++とし、その値を最後の値に設定し、小さいindexを前進する方向に1を加え、
アルゴリズムの複雑さ:
1回だけ遍歴するので複雑度はo(n)、nは配列の個数、
メモリ使用量:
2つのindex、1つのlast、1つのcountが必要であるため、除数グループを除いて、余分に消費されるメモリは固定されている、すなわちo(1)
コード:
考え方:
2つのindexは、0に最も近い2つの要素から2端に遍歴し、毎回2つのindexが存在する要素の絶対値を比較し、小さい値を取り、最後の1回の値と比較し、大きい場合はcount++とし、その値を最後の値に設定し、小さいindexを前進する方向に1を加え、
アルゴリズムの複雑さ:
1回だけ遍歴するので複雑度はo(n)、nは配列の個数、
メモリ使用量:
2つのindex、1つのlast、1つのcountが必要であるため、除数グループを除いて、余分に消費されるメモリは固定されている、すなわちo(1)
コード:
package test;
public class Test {
public static void main(String[] args) {
int[] is = new int[] { -10, -9, -9, -5, -4, -3, -3, -2, -1, 0, 1, 2, 5, 6, 7, 8, 9, 11, 13, 14 };
System.out.println(funOne(is, locateNumInSortedArray(0, is)));
}
/**
* , , 0,
* 0 0 2 index, count ,
* @param arr
* @param zeroIndex
* @return
*/
public static int funOne(int[] arr, int zeroIndex) {
int plusIndex = zeroIndex + 1, negativeIndex = zeroIndex - 1;
int last = arr[zeroIndex];
int count = 1;
while (negativeIndex >= 0 || plusIndex < arr.length) {
if (negativeIndex >= 0 && plusIndex < arr.length) {// both side continue
// x = small abs(...)
int x1;
int absNeg = Math.abs(arr[negativeIndex]);
if (absNeg > arr[plusIndex]) {
x1 = arr[plusIndex];
plusIndex += 1;
} else if (absNeg < arr[plusIndex]) {
x1 = absNeg;
negativeIndex -= 1;
} else {
x1 = arr[plusIndex];
plusIndex += 1;
negativeIndex -= 1;
}
if (x1 > last) {
count++;
last = x1;
}
} else if (negativeIndex >= 0) { // only negative site continue
int x2 = Math.abs(arr[negativeIndex]);
negativeIndex -= 1;
if (x2 > last) {
count++;
last = x2;
}
} else { // only plus site continue
int x3 = arr[plusIndex];
plusIndex += 1;
if (x3 > last) {
count++;
last = x3;
}
}
}
return count;
}
/**
* locate num in a sorted array
* @param num number to locate
* @param arr sorted array in asc order
* @return index of the num in array.If not find,-1 will be return.
*/
public static int locateNumInSortedArray(int num, int[] arr) {
if (arr.length == 0 || arr[0] > num || arr[arr.length - 1] < num) {
return -1;
}
int startIndex = 0, endIndex = arr.length - 1;
while (startIndex <= endIndex) {
int middleIndex = (startIndex + endIndex) >> 1;
if (num == arr[middleIndex]) {
return middleIndex;
} else if (num > arr[middleIndex]) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
return -1;
}
}