"Leetcode"--the object is sorted using the comparable interface

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.