problem 1 -- Two sum

很简单。没什么好说的。

主要学习了STL的find_ifbinary_search、和sort函数。



find_if函数原型为:

template <class InputIterator, class UnaryPredicate>
   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

实现等价于:

template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}

第三个参数pred是个函数指针或者函数对象,它的返回值应当可转化为bool类型,参数只有一个且应当声明为const。

find_if函数的返回值为(1)如果找到了,返回指向它的迭代器,(2)否则,返回last。



binary_search函数的原型为:

template <class ForwardIterator, class T>
  bool binary_search (ForwardIterator first, ForwardIterator last,
                      const T& val);
template <class ForwardIterator, class T, class Compare>
  bool binary_search (ForwardIterator first, ForwardIterator last,
                      const T& val, Compare comp);

实现等价于:

template <class ForwardIterator, class T>
  bool binary_search (ForwardIterator first, ForwardIterator last, const T& val)
{
  first = std::lower_bound(first,last,val);
  return (first!=last && !(val<*first));
}

binary_search函数的第三个参数为要查找的目标值。第四个参数为函数指针或者函数对象。它需要两个参数,返回一个bool型。

对于第一个版本,只有三个参数,使用operator < 函数来进行比较。第二个版本有四个参数,用第四个参数进行比较。

对于第一个版本,如果!(a < b) && !(b < a)那么a就与b相等。第二个版本类似,(!comp(a, b) && !comp(b, a)), 那么a与b相等。

find_if函数区别之一是: binary_search返回的是bool型而不是迭代器。所以binary_search函数只知道是否有这个值而无法得到准确的位置

        区别之二是:binary_search使用之前需要先排序。

如果迭代器不是random-access的也没关系,因为内部使用的是advance函数,只是这样复杂度就是o(n)了



sort函数原型

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

第三个参数是函数指针或者函数对象。
返回值是bool型,如果为真,表示a和b的偏序关系正确,为假表示不正确,需要交换。

完整代码如下:

class Solution {

struct MyStruct {
    int data;
    int original_pos;
};    

struct MyPred {
    MyPred(int d): data(d){}
    int data;
    bool operator() (MyStruct& tmp) {
        return tmp.data == data;
    }
};

public:
    vector<int>     twoSum(vector<int> &numbers, int target);
    static bool myCmp(const MyStruct &a, const MyStruct &b) {
        return a.data < b.data;
    }
private:

};

vector<int>    Solution::twoSum(vector<int> &numbers, int target) {
    vector<MyStruct>::iterator it;
    vector<MyStruct>::iterator pos;
    vector<MyStruct>    myStructVec;
    MyPred         myPred(target);

    int index = 1;
    for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); it++, ++index) {
        MyStruct tmp;
        tmp.data = *it;
        tmp.original_pos = index;
        myStructVec.push_back(tmp);
    }
    sort(myStructVec.begin(), myStructVec.end(), myCmp);

    for (it = myStructVec.begin(); it != myStructVec.end(); it ++) {
        myPred.data = target - it->data;
        if (myPred.data < it->data) {
            it = myStructVec.end();
            break;
        }
        if ((pos = find_if(it + 1, myStructVec.end(), myPred)) != myStructVec.end())
            break;
    }

    vector<int> ans;
    if (it != myStructVec.end()) {
        if (it->original_pos > pos->original_pos)
            swap(it, pos);
        ans.push_back(it->original_pos);
        ans.push_back(pos->original_pos);
    }

    return ans;
}

时间: 2024-11-06 20:31:06

problem 1 -- Two sum的相关文章

Project Euler:Problem 13 Large sum

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 919422133

Project Euler:Problem 82 Path sum: three ways

The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994. ????????13120163053

LeetCode Problem 1.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. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2

Whu 1603——Minimum Sum——————【单个元素贡献、滑窗】

Problem 1603 - Minimum Sum Time Limit: 2000MS   Memory Limit: 65536KB   Total Submit: 623  Accepted: 178  Special Judge: No Description There are n numbers A[1] , A[2] .... A[n], you can select m numbers of it A[B[1]] , A[B[2]] ... A[B[m]]  ( 1 <= B[

UVa 108 - Maximum Sum(最大连续子序列)

题目来源:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=44  Maximum Sum  Background A problem that is simple to solve in one dimension is often much more difficult to solve in more th

hdoj 1977 Consecutive sum II

Consecutive sum II Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2523    Accepted Submission(s): 1219 Problem Description Consecutive sum come again. Are you ready? Go ~~1    = 0 + 12+3+4    =

Minimum Sum(思维)

Problem 1603 - Minimum Sum Time Limit: 2000MS   Memory Limit: 65536KB    Total Submit: 563  Accepted: 156  Special Judge: No Description There are n numbers A[1] , A[2] .... A[n], you can select m numbers of it A[B[1]] , A[B[2]] ... A[B[m]]  ( 1 <= B

[LeetCode#110, 112, 113]Balanced Binary Tree, Path Sum, Path Sum II

Problem 1 [Balanced Binary Tree] Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Pr

HDU1977 Consecutive sum II【水题】

Consecutive sum II Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2237    Accepted Submission(s): 1093 Problem Description Consecutive sum come again. Are you ready? Go ~~ 1    = 0 + 1 2+3+4