• 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);
        }
    }; 
  • 相关阅读:
    C++虚函数机制(转)
    C/C++中extern关键字详解(转)
    (转)Javascript定义类(class)的三种方法
    使用HtmlAgilityPack实现对网页内容的抓取
    (转)Lucene Document getBoost(float) 和 setBoost(float)
    (转)Ajax中Get请求与Post请求的区别
    (转)Lucene.net实现自定义排序
    Lucene.net基本功能核心代码
    (转)使用Lucene.Net实现全文检索
    C#将html table 导出成excel
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759157.html
Copyright © 2020-2023  润新知