该算法反转N个整数的数组.我相信这个算法是O(N),因为对于每个循环迭代,四行代码执行一次,从而在4N时间内完成作业.
public static void reverseTheNumbers(int[] list) {
for (int i = 0; i < list.length / 2; i++) {
int j = list.length - 1 - i;
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
Run Code Online (Sandbox Code Playgroud) 为什么一个原始类型需要铸造而另一个不需要铸造?
/* This method uses stream operations to count how many numbers in a given array
* of integers are negative
*/
public static void countNegatives(int[] nums) {
long howMany = stream(nums) // or: int howMany = (int) stream(nums)
.filter(n -> n < 0)
.count();
System.out.print(howMany);
}
Run Code Online (Sandbox Code Playgroud)