Prove safety offer42: a digital array and S, the product of two outputs of the minimum number of

1 Title Description

  An incrementing input and a digital sorted array S, find the two numbers in the array, and so that they are exactly S, and if a plurality of digits equal to S, the product of the output of the minimum number of two.

Output Description:

  Corresponding to each test case, the output of two numbers, the first small output.

2 ideas and methods

  The array is already sorted, big and small pointers set two points at both ends, and if both greater than SUM, big left, SUM is less than, small right, once equal, it also happens to be at the same time both the product of the smallest pair (3 and 9,4 and 9,6 and 6, the minimum score is easy to see 3 and 9) , we can end up.

3 C ++ core code

 1 class Solution {
 2 public:
 3     vector<int> FindNumbersWithSum(vector<int> array,int sum) {
 4         vector<int> result;
 5         int len = array.size();
 6         if(len<=1)return result;
 7         int Sum;
 8         int small = 0;
 9         int big = len - 1;
10         while(small<big){
11             Sum = array[small] + array[big];
12             if(Sum>sum) big--;
13             else if(Sum<sum) small++;
14             else{
15                 result.push_back(array[small]);
16                 result.push_back(array[big]);
17                 break;
18             }
19         }
20         return result;
21     }
22 };
View Code

Reference material

https://blog.csdn.net/u012477435/article/details/83351659#_873

Guess you like

Origin www.cnblogs.com/wxwhnu/p/11422755.html
Recommended