[百度]数组A中任意两个相邻元素大小相差1,在其中查找某个数

时间:2023-03-09 06:30:22
[百度]数组A中任意两个相邻元素大小相差1,在其中查找某个数

一.问题来源及描述

  今天看了July的微博,发现了七月问题,有这个题,挺有意思的。

  数组A中任意两个相邻元素大小相差1,现给定这样的数组A和目标整数t,找出t在数组A中的位置。如数组:[1,2,3,4,3,4,5,6,5],找到4在数组中的位置。

二.算法分析及实现

  这道题目最差时间复杂度也是O(N)(递增或者递减的情况),所以重点在于能不能找到一种尽可能减少比较次数的方法。如数组:[1,2,3,4,3,4,5,6,5],找到4在数组中的位置。4和1比较,差为3,那么即使最好情况(递增或者递减),4也就是在a[3]的位置,可以跳过a[1]a[2]。这样在特定数组(目标值和a[1]相差很大)的情况下或许可以节省时间。

  所以得出规律:对于目标t,由当前位置a[i]比较开始,下一个可能位置为i = abs(a[i]-t)。

public class Solution {
public static Vector<Integer> ve = new Vector<Integer>(); public static void Find(int num[], int n, int target) {
if (n <= 0) return; for (int i = 0; i < n; ) {
if (num[i] == target) {
ve.add(i);
i += 2;
}
else i += Math.abs(num[i] - target);
}
return;
} public static void main(String args[]) {
ve.clear();
int num[] = {1, 2, 3, 2, 3, 4, 3, 2, 3};
int target = 4;
Find(num, num.length, target);
for (int i : ve)
System.out.println(i + " ");
}
}

  为什么+2?比如"4,3,4"。+1肯定不是。