How to solve the problem of input ordered array by the sum of two numbers in LeetCode
Editor to share with you how to solve the problem of the sum of two numbers input ordered array in LeetCode. I hope you will get something after reading this article. Let's discuss it together.
0x01, brief description of the problem
Given an ordered array that has been arranged in ascending order, find two numbers so that the sum of them is equal to the target number. The function should return these two subscript values index1 and index2, where index1 must be less than index2.
Description:
The returned subscript values (index1 and index2) are not zero-based.
You can assume that each input only corresponds to a unique answer, and you cannot reuse the same element.
'0x02, exampl
Example:
Input: numbers = [2,7,11,15], target = 9 output: [1Magne2] explain: the sum of 2 and 7 equals the number of targets 9. So index1 = 1, index2 = 2.
0x03, ideas for problem solving
This problem is solved by the idea of double pointers.
0x04, problem solving procedure
Public class TwoSumTest3 {public static void main (String [] args) {int [] numbers = {2,7,11,15}; int target = 9; int [] twoSum = twoSum (numbers, target); for (int num: twoSum) {System.out.print (num + "\ t");}}
Public static int [] twoSum (int [] numbers, int target) {if (numbers = = null | | numbers.length = = 0) {return new int [0];} int I = 0; int j = numbers.length-1; while (I
< j) { if (numbers[i] + numbers[j] == target) { return new int[]{i+1, j+1}; } else if (numbers[i] + numbers[j] < target) { i++; } else if (numbers[i] + numbers[j] >Target) {jmurmuri;}} return new int [] {- 1,-1};}}
0x05, photo version of the problem solving program
After reading this article, I believe you have some understanding of "how to solve the problem of entering ordered arrays in LeetCode". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!