已排序数组 a,求其元素的绝对值 共有多少个不同的值?
思路:
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;
}
}