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);
        }
    }; 
  • 相关阅读:
    WebSocket
    使用fiddler将网站上的css js重定向至本地文件
    chrome浏览器调试线上文件映射本地文件
    xul 创建一个按钮
    模板小程序】求小于等于N范围内的质数
    哈希-------开放寻址法-------暴雪哈希
    建造者模式(build pattern)-------创造型模式
    抽象工厂模式(abstract factory pattern)------创造型模式
    工厂模式(factory pattern) ------创造型模式
    文件名中含有连续字符abc,相应文件中也含有字符串abc
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759157.html
Copyright © 2011-2022 走看看