LeetCode 1 — Two Sum(C++ Java Python)

來源:互聯網
上載者:User

題目:http://oj.leetcode.com/problems/two-sum/

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

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

題目翻譯:

給定一個整數數組,找到兩個數,使得它們的和等於一個特定的目標數。
函數twoSum應返回兩個數的索引(index),使它們加起來等於目標,其中索引1必須小於索引2。注意返回的答案(包括索引1和索引2 )不是從零開始的。
可以假設每個輸入有且僅有一個答案。
輸入:數字 = {2,7,11,15},目標 = 9
輸出:索引1 = 1,索引2 = 2

分析:

        首先複製一份array,對其進行排序,找到合格兩個數,再在原數組裡找到index。

C++實現:

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        // Note: The Solution object is instantiated only once and is reused by 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實現:

public class Solution {    public int[] twoSum(int[] numbers, int target) {        // Note: The Solution object is instantiated only once and is reused by 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實現:

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

        感謝閱讀,歡迎評論。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.