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);
        }
    }; 
  • 相关阅读:
    express 的安全中间件 helmet 简介
    一个设置过期时间的方案
    vscode 中的 vue 格式化
    linux 中部署不同版本 node.js 并同时使用的方案
    webpack 多页面模式配置
    1.assert
    我是一个线程(转)
    Android FragmentTransactionExtended:使Fragment以多种样式动画切换
    Android ORM应用开发框架KJFrameForAndroid使用详解
    Android Studio插件推荐(PreIOC,GsonFormat)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759157.html
Copyright © 2011-2022 走看看