10
10 10 10 10 20 20 30 30 40 40
输出例子 1:
30
解答:
-
/*简单,时间复杂度也低*/ #
-
include < iostream > using namespace std;
-
int main()
-
{
-
int n, t = 0, syn = 0;
-
int price[1000] = {
-
0
-
};
-
cin >> n;
-
while(n--)
-
{
-
cin >> t;
-
price[t] = 1;
-
}
-
t = 0;
-
for(int i = 0; i < 1000; i++)
-
{
-
if(price[t] && syn < 3) syn++;
-
if(syn == 3) break;
-
t++;
-
}
-
syn == 3 ? cout << t : cout << -1;
-
}
2、一个数轴上共有 N 个点,第一个点的坐标是度度熊现在位置,第 N-1 个点是度度熊的家。现在他需要依次的从 0 号坐标走到 N-1 号坐标。
但是除了 0 号坐标和 N-1 号坐标,他可以在其余的 N-2 个坐标中选出一个点,并直接将这个点忽略掉,问度度熊回家至少走多少距离?
解答:
从 N-2 个坐标中选出一个点,并直接将这个点忽略掉。直接忽略一个点只会直接影响到,这个节点前后节点的距离。这个 影响的距离我们暂且命名为优化距离,将所有节点按顺序组成三个节点的集合,通过这种方式只需要通过一次循环便能得到结果。
优化距离越大说明如果去掉这个集合的中点元素将会使得总距离越短,下面上代码。
-
import
-
java.util.
-
Scanner;
-
publicclass
-
Main
-
{
-
publicstaticvoid
【一线大厂Java面试题解析+核心总结学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
main(String[] args)
-
{
-
Scanner
-
scanner = new
-
Scanner(System.in);
-
int
-
length = scanner.nextInt();
-
int[] arrays = newint[length];
-
for(int i = 0; i < length; i++)
-
{
-
arrays[i] = scanner.nextInt();
-
}
-
/**
-
* sum 总距离
-
* repetition 三个节点 中被重复计算的总距离
-
* select 优化距离最大的 三个节点两两相加的距离
-
* add 三个结尾距离为 max 中 头尾节点的距离
-
* last 最后三个节点中 尾距离没有被计算两次 需要加上
-
* optimizeDistance 优化距离
-
*/
-
int
-
sum = 0,
-
int
-
repetition = 0,
-
intselect = 0,
-
int
-
add = 0,
-
intlast = 0,
-
int
-
optimizeDistance = 0;
-
for(int i = 0; i <= (arrays.length - 3); i++)
-
{
-
intbegin = arrays[i];
-
int
-
mid = arrays[i + 1];
-
intend = arrays[i + 2];
-
//三个点之间的距离
-
int
-
threePointDistance = Math.abs(mid - begin) + Math.abs(end - mid);
-
//两个点之间的距离 即被多次计算待会需要减掉的距离
-
int
-
twoPointDistance = Math.abs(end - mid);
-
int
-
contrast = threePointDistance - Math.abs(begin - end);
-
repetition += twoPointDistance;
-
sum += threePointDistance;
-
last = twoPointDistance;
-
if(contrast > optimizeDistance)
-
{
-
optimizeDistance = contrast;
-
select = threePointDistance;
-
add = Math.abs(end - begin);
-
}
-
}
-
System.