Algorithm

这个任务需要你注册并登陆:https://practiceit.cs.washington.edu/

如果你登陆成功,可以开始完成以下任务:

注意:每道题目先点击右上角的“Show Header”,方便了解函数的参数和返回值。

For Q10, you want to create a new array with appropriate length in the beginning of the function.

Optional Question

OQ1: findLongestSubarray

Write a function int findLongestSubarray(int[] arr) that takes in an array of integers and returns the length of the longest subarray in which the numbers are in ascending order. For example, if the input array is {2, 6, 4, 8, 10, 15}, the function should return 4, because the longest subarray in which the numbers are in ascending order is {4, 8, 10, 15}.

Sample Code is below:

public class Main {
  public static int findLongestSubarray(int[] arr) {
    // Your code here
  }

  public static void main(String[] args) {
    // Test the function with different input arrays
    int[] array = {2, 6, 4, 8, 10, 15};
    System.out.println(findLongestSubarray(array));// should return 4
  }
}

OQ2: findFirstDuplicate

Implement a function int findFirstDuplicate(int[] arr) that takes in an array of integers and returns the first duplicate number in the array. If there are no duplicate numbers, the function should return -1.

For example, if the input array is {2, 3, 1, 5, 2, 4}, the function should return 2, because 2 is the first duplicate number in the array.

Sample Code is below:

public class Main {
  public static int findFirstDuplicate(int[] arr) {
    // Your code here
    
  }

  public static void main(String[] args) {
    // Test the function with different input arrays
    int[] arr1 = {2, 3, 1, 5, 2, 4};
    int[] arr2 = {1, 2, 3, 4, 5};
    int[] arr3 = {5, 3, 2, 5, 1, 4};
    System.out.println(findFirstDuplicate(arr1)); // should return 2
    System.out.println(findFirstDuplicate(arr2)); // should return -1
    System.out.println(findFirstDuplicate(arr3)); // should return 5
  }
}

Last updated