【LeetCode刷题-双指针】--259.较小的三数之和

259.较小的三数之和

方法:排序+双指针

java 复制代码
class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int k = 0;
        for(int i = 0;i<nums.length;i++){
            int start = i + 1,end = nums.length - 1;
            while(start < end){
                int sum = nums[start] + nums[end] + nums[i];
                if(sum < target){
                    k += (end - start);  //因为数组排好序了,所以start到end中的数都小于target
                    start++;
                }
                if(sum >= target){
                    end--;
                }
            }
        }
        return k;
    }
}
相关推荐
会编程的土豆3 分钟前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
炘爚13 分钟前
深入解析printf缓冲区与fork进程复制机制
linux·运维·算法
迈巴赫车主1 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
Kethy__2 小时前
计算机中级-数据库系统工程师-数据结构-查找算法
数据结构·算法·软考·查找算法·计算机中级
所以遗憾是什么呢?2 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
xiaoye-duck3 小时前
《算法题讲解指南:递归,搜索与回溯算法--综合练习》--14.找出所有子集的异或总和再求和,15.全排列Ⅱ,16.电话号码的字母组合,17.括号生成
c++·算法·深度优先·回溯
OOJO3 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
茉莉玫瑰花茶3 小时前
数据结构 - 并查集
数据结构
汀、人工智能3 小时前
05 - 函数基础
数据结构·算法·数据库架构·05 - 函数基础