@XQF
2018-03-07T14:57:36.000000Z
字数 550
阅读 1490
数据结构与算法
问题描述:有一个升序排列的数组,数组中可能有正数,负数,0.求数组中元素的绝对值最小的数。
,。,。,还用,。,。
跟记录最值一个原理,只不过要记住索引求正负
public class Solution {public int getMinAbs(int[] nums) {if (nums == null || nums.length == 0) {return -1;}int min = Math.abs(nums[0]);int index = 0;int temp;for (int i = 0; i < nums.length; i++) {temp = Math.abs(nums[i]);if (temp < min) {min = temp;index = i;}}if (nums[index] < 0) {return -min;} else {return min;}}public static void main(String[] args) {Solution solution = new Solution();// int[] nums = {-10, -5, -2, 7, 15, 50};int[] nums = {-10};int result = solution.getMinAbs(nums);System.out.println("result:" + result);}}
