• [LeetCode] 3Sum Smaller


    Problem Description:

    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?


    Sort nums first and then fix the left index (i) at each time while adjusting the middle and right indexes (j, k). The following code should be self-explanatory.

     1 class Solution {
     2 public:
     3     int threeSumSmaller(vector<int>& nums, int target) {
     4         sort(nums.begin(), nums.end());
     5         int n = nums.size(), ans = 0, i, j, k;
     6         for (int i = 0; i < n - 2; i++) {
     7             int j = i + 1, k = n - 1;
     8             while (j < k) {
     9                 if (nums[i] + nums[j] + nums[k] >= target) k--;
    10                 else {
    11                     ans += (k - j);
    12                     j++;
    13                 }
    14             }
    15         }
    16         return ans;
    17     }
    18 };
  • 相关阅读:
    在eclipse中进行HotSpot的源码调试
    CentOS6.5上编译OpenJDK7源码
    商城楼层跳转
    javascript原生百叶窗
    javascript原生轮播
    Canvas计时器
    纯js模拟 radio和checkbox控件
    纯js日历
    关于匿名函数,闭包和作用域链
    端口占用问题
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4736809.html
Copyright © 2020-2023  润新知