当前位置:网站首页>Array target two integers and return their array subscripts

Array target two integers and return their array subscripts

2022-06-10 10:33:00 InfoQ

1、 Background
Given an array of integers nums And an integer target value target, Please find the sum in the array as the target value target The two integers of , And return their array subscripts .

  • You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer .
  • You can return the answers in any order .
2、 Code implementation
public class Solution {

 public static void main(String[] args) {
 int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
// System.out.println(containsDuplicate(nums));
 System.out.println(maxSubArray(nums));
 }
 /**
 *  Give you an array of integers nums, Please find a continuous subarray with the largest sum ( A subarray contains at least one element ), Return to its maximum and , A subarray is a continuous part of an array
 *
 * @param nums
 * @return
 */
 public static int maxSubArray(int[] nums) {
 if (nums.length == 1) {
 return nums[0];
 }
 int sum = Integer.MIN_VALUE;
 int count = 0;
 for (int i = 0; i < nums.length; i++) {
 count += nums[i];
 // Take the maximum value of interval accumulation ( It is equivalent to continuously determining the termination position of the maximum subsequence )
 sum = Math.max(sum, count);
 if (count <= 0) {
 // It is equivalent to resetting the starting position of the maximum sub order , Because when you encounter a negative number, you must pull down the sum
 count = 0;
 }
 }
 return sum;
 }
}
3、 Result display
6

Process finished with exit code 0

原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101012163241.html