zoukankan      html  css  js  c++  java
  • 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

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> datas=numbers;
            quicksort(datas,0,datas.size()-1);
            vector<int> result;
            int left=0;
            int right=datas.size()-1;
            while(datas[left]+datas[right]!=target)
            {
                while(datas[left]+datas[right]<target)
                    left++;
                while(datas[left]+datas[right]>target)
                    right--;
            }
            for(int i=0;i<numbers.size();i++)
            {
                if(numbers[i]==datas[left] || numbers[i]==datas[right])
                    result.push_back(i+1);
                if(result.size()==2)
                    break;
            }
            return result;
        }
    private:
        void quicksort(vector<int> & datas,int left,int right)
        {
            if(left>=right) 
                return;
            int l=left;
            int r=right;
            int m=datas[(l+r)/2];
            while(l<=r)
            {
                while(datas[l]<m) l++;
                while(datas[r]>m) r--;
                if(l>right || r<left || l>=r)
                    break;
                
                int tmp=datas[l];
                datas[l]=datas[r];
                datas[r]=tmp;
                l++;r--;
            }
            
            quicksort(datas,left,l-1);
            quicksort(datas,r+1,right);
        }
    }; 
  • 相关阅读:
    java基础知识:私有成员变量
    分布式架构:概述一
    java基础知识:内存
    原油期货价格跌至-37美元/桶的影响
    贷款利息
    java基础知识:IntelliJ IDEA的基础设置
    正则表达式的常用方法
    http服务器三:自己写一个服务器实现转发功能
    bzoj3875: [Ahoi2014&Jsoi2014]骑士游戏(用spfa解决有后效性的dp)
    bzoj2118: 墨墨的等式(巧妙的单源最短路+priority_queue)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759157.html
Copyright © 2011-2022 走看看