zoukankan      html  css  js  c++  java
  • 【LeetCode】259 3Sum Smaller

    题目:

    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

    For example, given nums = [-2, 0, 1, 3], and target = 2.
    
    Return 2. Because there are two triplets which sums are less than 2:
    
    [-2, 0, 1]
    [-2, 0, 3]

    Follow up:

    Could you solve it in O(n^2) runtime?

    题解:

      (我没舍得花钱。。。咳咳,这样不太好QAQ,代码都没有提交过,所以以后来看得注意一下代码的正确性。)

      老规矩,第一个想法是啥?必须的暴力解啊,哈哈,虽然时间复杂度是O(n^3);这里

    Solution 1 ()

     1 class Solution {
     2 public:
     3     int threeSumSmaller(vector<int>& nums, int target) {
     4         int cnt = 0;
     5         sort(nums.begin(), nums.end());
     6         int n = nums.size();
     7         for(int i=0; i<n-2; i++) {
     8             if(i>0 && nums[i] == nums[i-1]) continue;
     9             for(int j=i+1; j<n-1; j++) {
    10                 if(j>i+1 && nums[j] == nums[j-1]) continue;
    11                 for(int k=j+1; k<n; k++) {
    12                     if(k>j+1 && nums[k] == nums[k-1]) continue;
    13                     if(nums[i] + nums[j] + nums[k] < target) cnt++;
    14             else break;
    15                 }
    16             }
    17         }
    18     }
    19 };

      若想时间复杂度为O(n^2),那么就需要和之前的3Sum题目一样,两指针为剩余数组的头尾指针,搜索遍历。这里需要注意的是,当sum<target时,cnt需要加上k-j,而不是cnt++,因为数组已经排好序,若尾指针当处于位置k时满足条件,则j<position<=k的pos都满足这个条件,故cnt需加上k-j.

    Solution 2 ()

     1 class Solution {
     2 public:
     3     int threeSumSmaller(vector<int>& nums, int target) {
     4         int cnt = 0;
     5         sort(nums.begin(), nums.end());
     6         int n = nums.size();
     7         for(int i=0; i<n-2; i++) {
     8             if(i>0 && nums[i] == nums[i-1]) continue;
     9             int j = i + 1, k = n - 1;
    10             while(j<k) {
    11                 int sum = nums[i] + nums[j] + nums[k];
    12                 if(sum < target) {
    13                     cnt += k - j;
    14                     j++;
    15                 }
    16                 else k--;
    17             }    
    18         }
    19         return cnt;
    20     }
    21 };
  • 相关阅读:
    URAL——DFS找规律——Nudnik Photographer
    URAL1353——DP——Milliard Vasya's Function
    URAL1203——DPor贪心——Scientific Conference
    递推DP HDOJ 5389 Zero Escape
    区间DP UVA 1351 String Compression
    树形DP UVA 1292 Strategic game
    Manacher HDOJ 5371 Hotaru's problem
    同余模定理 HDOJ 5373 The shortest problem
    递推DP HDOJ 5375 Gray code
    最大子序列和 HDOJ 1003 Max Sum
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6715599.html
Copyright © 2011-2022 走看看