百度面试题:求绝对值最小的数
来源:互联网 发布:php fetch array 编辑:程序博客网 时间:2024/06/05 10:21
有一个已经排序的数组(升序),数组中可能有正数、负数或0,求数组中元素的绝对值最小的数,要求,不能用顺序比较的方法(复杂度需要小于O(n)),可以使用任何语言实现
例如,数组{-20,-13,-4, 6, 77,200} ,绝对值最小的是-4。
算法实现的基本思路
找到负数和正数的分界点,如果正好是0就是它了,如果是正数,再和左面相邻的负数绝对值比较,如果是负数,取取绝对值与右面正数比较。还要考虑数组只有正数或负数的情况。
我根据这个思路用Java简单实现了一个算法。大家有更好的实现方法欢迎跟帖
public class MinAbsoluteValue { private static int getMinAbsoluteValue(int[] source) { int index = 0; int result = 0; int startIndex = 0; int endIndex = source.length - 1; // 计算负数和正数的分界点 while(true) { index = startIndex + (endIndex - startIndex) / 2; result = source[index]; if(result==0) { return 0; } else if(result > 0) { if(index == 0) { break; } if(source[index-1] >0) endIndex = index - 1; else if(source[index-1] ==0) return 0; else break; } else { if(index == endIndex) break; if(source[index + 1] < 0) startIndex = index + 1; else if(source[index + 1] == 0) return 0; else break; } } // 根据分界点计算绝对值最小的数 if(source[index] > 0) { if(index == 0 || source[index] < Math.abs(source[index-1])) result= source[index]; else result = source[index-1]; } else { if(index == source.length - 1 || Math.abs(source[index]) < source[index+1]) result= source[index]; else result = source[index+1]; } return result; }public static void main(String[] args) throws Exception{int[] arr1 = new int[]{-23,-22,-3,-2,1,2,3,5,20,120};int[] arr2 = new int[]{-23,-22,-12,-6,-4};int[] arr3 = new int[]{1,22,33,55,66,333};int value = getMinAbsoluteValue(arr1);System.out.println(value);value = getMinAbsoluteValue(arr2);System.out.println(value);value = getMinAbsoluteValue(arr3);System.out.println(value);}}
李宁的新浪微博 http://weibo.com/androidguy 欢迎关注
- 百度面试题:求绝对值最小的数
- 百度面试题:求绝对值最小的数
- 百度面试题:求绝对值最小的数
- 百度面试题:求绝对值最小的数
- 百度面试题:求绝对值最小的数
- 百度面试题:求一个已排序的数组中绝对值最小的元素
- 百度面试题:求一个已排序的数组中绝对值最小的元素
- 百度面试题:从已排序的数组中求绝对值最小的元素
- 求绝对值最小的数
- 求绝对值最小的数
- 求绝对值最小的数
- 求绝对值最小的数
- [经典面试题][百度]求比指定数大且最小的“不重复数”
- 百度面试题 求比N大的最小“不重复数”
- [面试题] 求数组两两之差绝对值最小的值
- 【转】[面试题] 求数组两两之差绝对值最小的值
- 【百度面试题】把数组排成最小的数
- 【百度面试题】把数组排成最小的数
- CRC16校验
- web项目加解密
- JDK源码学习之Vector、Stack与LinkedList
- Cmake 模板和语法
- 为什么如此获取Java数组的长度
- 百度面试题:求绝对值最小的数
- Web服务器 Mongoose 的介绍与安装
- WP7 Isolated Storage 系列 - 4.读取和存储文本文件
- VS2008 快捷键汇总
- 搜集的各种推荐书籍(不晓得这辈子读得完不!)
- where T : class的含义
- Textarea限制输入内容长度
- ASP.NET MVC3学习--视图和模型(5)
- 同步~异步~阻塞~非阻塞