如何在具有正值和负值的数组中找到最大的负值?
我需要返回最大的负值,如果没有负值,我需要返回零。 这是我有的:
public int greatestNegative(int[] list) { for (int i = 0; i < list.length; i++) { if (list[i] = 0) { if (list[j - negativeNumbers] < 0) { list[j] = 0; list[j - 1] = list[j - negativeNumbers]; negativeNumbers--; j--; } else{ list[j] = list[j - negativeNumbers]; j--; } } }
您只需要将此问题视为两个步骤:
- 只考虑list []中的负值。
- 在负值内的循环中,更新当前结果if(result == 0)或(value> result)。
码:
public int greatestNegative(int[] list) { int result = 0; for (int i = 0; i < list.length; i++) { if (list[i] < 0) { if (result == 0 || list[i] > result) { result = list[i]; } } } return result; }
只需添加条件即可找到最大数量。
public static int greatestNegative(int[] list) { int max = Integer.MIN; boolean set = false; for (int i = 0; i < list.length; i++) { if (list[i] < 0 && list[i] > max) { max = arr[i]; set = true; } } if (!set) max = 0; return max; }
这是返回最小负数的代码
public static int greatestNegative(int[] list) { int negativeNumbers = 0; for (int i = 0; i < list.length; i++) { if (list[i] < 0 && list[i] < negativeNumbers) negativeNumbers = list[i]; } return negativeNumbers; }
输入:1,2,-3,5,0,-6
输出:-6
输入:1,2,3,5,0,6
输出:0
如果您需要最大负数,则对第一个负数进行排序
import java.util.Arrays; class Main { public static void main(String[] args) { int arr[] = { 2, 4, 1, 7,2,-3,5,-20,-4,5,-9}; System.out.println(greatestNegative(arr)); } private static int greatestNegative(int[] arr) { Arrays.sort(arr); for (int i = arr.length - 1; i >= 0; i--) { if (isNegative (arr[i])) { return arr[i]; } } return 0; } private static boolean isNegative (int i) { return i < 0; } }
输出:-3
请检查以下代码,首先从数组中计算小数,然后检查是否为正数? 如果是,则返回0否则返回否定。
public static int greatestNegative(int[] list) { int negativeNumbers = Integer.MAX_VALUE; for (int i = 0; i < list.length; i++) { if (list[i] < negativeNumbers) negativeNumbers = list[i]; } if(negativeNumbers >=0) return 0; else return negativeNumbers; }
你必须尝试这个….
public int greatestNegative(int[] list) { int negNum = 0; for(int i=0; i
首先将“maxNegative”值设置为0.然后指定您遇到的第一个负数。 之后,只分配更高的负数。 如果没有负数,则“maxNegative”仍为零。
public static void main(String[] args) { int arr[] = {2, -1, 4, 1, 0, 7, 2, -3, 5, 9, -4, 5, -9}; int maxNegative = 0; for (int i = 0; i < arr.length; i++) { if (maxNegative == 0 && arr[i] < maxNegative) { // Set the first negative number you come across maxNegative = arr[i]; } else if (maxNegative < arr[i] && arr[i] < 0) { // Set greater negative numbers maxNegative = arr[i]; } } System.out.println(maxNegative); }
结果:
-1
Java 8
然后有一些流,允许您使用一行代码执行此操作。
public static void main(String[] args) { int arr[] = {2, 4, 1, 0, 7, 2, -3, 5, 9, -4, 5, -9}; int maxNegative = Arrays.stream(arr).filter(a -> a < 0).max().orElse(0); System.out.println(maxNegative); }
结果:
-3