Title, num
Test instructions: Given an array of integers and a target value, it is required to find two numbers in the array so that their sum is equal to the target value, and returns a subscript of two numbers
Idea: 1. If violence is used, the time complexity is O (n^2)
2. You can sort all the numbers first, starting with the maximum and minimum values and then moving according to the comparison with the target values, knowing that the results are found and the time complexity is O (Nlog (n))
Knowledge Points: The use of comparable interfaces, the natural ordering of objects using them, related articles
public class Solution {static class Node implements comparable<node>{int val,index; Public Node (int v,int i) {val = v; index = i; } public int compareTo (Node o) {return this.val-o.val; }} public int[] Twosum (int[] numbers,int target) {int[] xy = new INT[2]; node[] nodes = new Node[numbers.length]; for (int i = 0;i < numbers.length;i++) {Nodes[i] = new Node (numbers[i],i+1); } arrays.sort (nodes); int i = 0,j = numbers.length-1; while (I < j) {if (Nodes[i].val+nodes[j].val = = target) {break; } else if (Nodes[i].val+nodes[j].val < target) i++; else j--; } xy[0] = Nodes[i].index <= nodes[j].index? Nodes[i].index:nodes[j].index; XY[1] = nodes[i].index > Nodes[j].index?nodes[i].index:nodes[j].index; return XY; } }
"Leetcode"--the object is sorted using the comparable interface