日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode1:Two Sum

發布時間:2023/11/30 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode1:Two Sum 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原題連接:傳送門

Given an array of integers, return?indices?of the two numbers such that they add up to a specific target.

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

題目大意:

給一個數組和一個特定的值,返回數組中兩個數的下標,使得這兩個數的和等于給定的數,還要求給出的結果按順序排放,如:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

這里我們對數組中的每個數都要保留兩個信息,一個是數本身的值,一個是數的下標。因此我們可以定義一個結構體:

struct Node {int val;int idx; };用val來存儲數組中的數值,用idx來存儲數的下標。

這是一個典型的雙指針問題,將數組升序排序后,從左右兩邊向中間移動,檢查兩個位置上數的和,如果和等于給定的值target,說明找到了這對數,把下標保存在vector<int>中接口;如果和大于target,說明有指針位置的數較大,將右側游標向左移動,左側游標不動;如果和小于target,說明左側游標位置的數較小,將左側游標右移,右側游標不動,直到找到合適的數對。

可是傳過來的參數不是升序排列的,需要我們進行排序。C++中有一個函數sort,下面介紹下C++庫中的sort函數。

1.定義:定義在<algorithm>頭文件中;

2.函數原型:

  • template<?class?RandomAccessIterator?>
    void?sort(?RandomAccessIterator first, RandomAccessIterator last?);
  • template<?class?RandomAccessIterator,?class?Compare?>
    void?sort(?RandomAccessIterator first, RandomAccessIterator last, Compare comp?);

即sort有兩個重載函數,一個需要兩個參數:first和last;另一個需要三個參數,first、last和自定義比較函數comp。

sort函數對在[first,last)區間內的元素按照升序排列。函數對相同元素不一定保留原來的次序,同時,第一個函數使用<操作符進行比較,第二個函數使用comp進行比較。

3.參數:

  • first、last:要比較元素的范圍,是一個迭代器;
  • comp:比較函數,如果第一個參數小于第二個參數返回true。自定義的函數必須滿足如下形式:
    bool?cmp(const?Type1?&a,?const?Type2?&b);

4.返回值:none

5.時間復雜度:
O(N·log(N))

6.例子:

#include <algorithm> #include <functional> #include <array> #include <iostream>int main() {std::array<int, 10> s{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};std::sort(s.begin(), s.end());for (int a : s) {std::cout << a << " ";} std::cout << '\n';std::sort(s.begin(), s.end(), std::greater<int>());for (int a : s) {std::cout << a << " ";} std::cout << '\n'; }結果:

0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0


因此,我們需要給出自己的comp函數來比較Node:

bool cmp(Node a,Node b) {return a.val<b.val; }
只比較val值即可。

然后,就可以按照上面的描述寫代碼了:

struct Node {int val;int idx; }; bool cmp(Node a,Node b) {return a.val<b.val; } class Solution { public:vector<int> twoSum(vector<int>& nums, int target) {vector<int> ret(2);vector<Node> nodes;for(int i=0;i<nums.size();i++){Node node;node.val=nums[i];node.idx=i;nodes.push_back(node);}sort(nodes.begin(),nodes.end(),cmp);for(int i=0,j=nodes.size()-1;i!=j;){int sum=nodes[i].val+nodes[j].val;if(sum==target){ret[0]=nodes[i].idx<nodes[j].idx?nodes[i].idx:nodes[j].idx;ret[1]=nodes[i].idx+nodes[j].idx-ret[0];break;}else if(sum<target)i++;elsej--;}return ret;} };
從上面的代碼中可以看到,如果沒有sort一步,處理過程只需將nodes遍歷一遍。

總結

以上是生活随笔為你收集整理的Leetcode1:Two Sum的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。