[关闭]
@XQF 2018-03-07T22:57:36.000000Z 字数 550 阅读 1361

如何求绝对值最小的数?

数据结构与算法


问题描述:有一个升序排列的数组,数组中可能有正数,负数,0.求数组中元素的绝对值最小的数。

,。,。,还用,。,。

跟记录最值一个原理,只不过要记住索引求正负

  1. public class Solution {
  2. public int getMinAbs(int[] nums) {
  3. if (nums == null || nums.length == 0) {
  4. return -1;
  5. }
  6. int min = Math.abs(nums[0]);
  7. int index = 0;
  8. int temp;
  9. for (int i = 0; i < nums.length; i++) {
  10. temp = Math.abs(nums[i]);
  11. if (temp < min) {
  12. min = temp;
  13. index = i;
  14. }
  15. }
  16. if (nums[index] < 0) {
  17. return -min;
  18. } else {
  19. return min;
  20. }
  21. }
  22. public static void main(String[] args) {
  23. Solution solution = new Solution();
  24. // int[] nums = {-10, -5, -2, 7, 15, 50};
  25. int[] nums = {-10};
  26. int result = solution.getMinAbs(nums);
  27. System.out.println("result:" + result);
  28. }
  29. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注