1, and a certain time to find the number of two in the array

Source: Internet
Author: User

Title Requirements:

Given an array of integers and a target value, find the two numbers in the array and the target values.

You can assume that each input corresponds to only one answer, and that the same element cannot be reused.

Ideas:

Sum must be, to ask two numbers, you need two pointers, two pointers a large one small do not want to wait, first let the small pointer do not move, let the large pointer move backwards, know that appears greater than or equal to the need. Equal to the output result, the small pointer moves backward one bit, and a pointer that is larger than the time of the move appears greater than or equal to the required sum. And so on, the result is obtained. Equivalent to a reverse "median theorem".

Code:

 Public classOne { Public Static voidMain (string[] args) {int[] Nums = {1,2,3,4,5,6,7,8,9}; inttarget = 10;  for(inta=0;a<nums.length;a++)    {         for(intb=a+1;b<nums.length;b++)             if(Nums[a]+nums[b] = =target) System.out.println ("There has" +nums[a]+ "and" +nums[b]+ "=" +target); }}}

1, and a certain time to find the number of two in the array

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.