Leetcode 1-two Sum (c + + Java Python)

Source: Internet
Author: User

Title: http://oj.leetcode.com/problems/two-sum/

Given an array of integers, find two numbers such this they add up to a specific target number.

The function twosum should return indices of the two numbers such this they add up to the target where index1 must is Les S than Index2. Please note this your returned answers (both INDEX1 and index2) are not zero-based.

You may assume this each input would have exactly one solution.

Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2

Title translation:

Given an array of integers, find two numbers so that their sum equals a specific number of targets.
function Twosum should return two-digit indexes (index) to add up to the target, where Index 1 must be less than index 2. Note that the answer returned (including Index 1 and index 2) is not zero-based.
You can assume that each input has and has only one answer.
Input: Number = {2,7,11,15}, target = 9
Output: Index 1 = 1, index 2 = 2

Analysis:

First copy an array, sort it, find two numbers that match the condition, and then find index in the original array.

C + + implementation:

Class Solution {public:vector<int> twosum (vector<int> &numbers, int target) {//Note:the S
        Olution object is instantiated only once and are reused by the each test case.
        vector<int> num = numbers;
        
        Std::sort (Num.begin (), Num.end ());
        int length = Numbers.size ();
        int left = 0;
        int right = Length-1;
        
        int sum = 0;
        
        Vector<int> index;
        	
            while (left < right) {sum = Num[left] + num[right];  if (sum = = target) {for (int i = 0; i < length; ++i) {if (numbers[i)
            		= = = Num[left]) {index.push_back (i + 1);
            		else if (numbers[i] = = Num[right]) {index.push_back (i + 1);
            		} if (index.size () = = 2) {break;
              }
            	}  Break
            else if (sum > Target) {--right;
            else {++left;
    } return index; }
};

Java implementation:

public class Solution {public int[] twosum (int[] numbers, int target) {//Note:the Solution the object is Insta
        Ntiated only once and are reused by the each test case.
		int[] num = Numbers.clone ();

		Arrays.sort (num);
		int length = Numbers.length;
		int left = 0;
		int right = Length-1;

		int sum = 0;

		Arraylist<integer> index = new arraylist<integer> ();

			while (left < right) {sum = Num[left] + num[right]; 
					if (sum = = target) {for (int i = 0; i < length; ++i) {if (numbers[i] = Num[left]) {Index.add (i + 1);
					else if (numbers[i] = = Num[right]) {Index.add (i + 1);
					} if (index.size () = = 2) {break;
			}} break;
			else if (sum > Target) {--right;
			else {++left;

		} int[] result = new INT[2];
		Result[0] = index.get (0);

		RESULT[1] = index.get (1);
	return result;

		public static void Main (string[] args) {Solution slt = new Solution (); int[] Numbers ={2, 7, 11, 15};

		int target = 9;

		int[] index = new int[2];

		index = slt.twosum (numbers, target);
	System.out.println ("index1=" + index[0] + ", index2=" + index[1]); }
}

Python implementations:

Class Solution:
    # @return A tuple, (index1, Index2)
    def twosum (self, num, target):
     
        numbers = sorted (num)

        length = Len (num) Left
        = 0 Right
        = length-1

        index = [] While left

        < right: 
            sums = Numbers[left] + Numbers[right]

            if sums = = target: For
                I in range (length):
                    if num[i] = = Numbers[left]:
                        index.append (i + 1)
                    elif num[i] = = Numbers[right]:
                        index.append (i + 1)
                    
                    if len (index) = 2
                        :
            break break Elif sums > Target: Right
                -= 1
            Else: Left
                + 1 result

        = tuple (index)

        return result

Thank you for reading and welcome comments.

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.