题目 LeetCode15
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解题思路
思路1:暴力求解,3 层循环。时间复杂度 O(nnn)
思路2:2 层循环,第 1 层循环遍历数组,作为 target,第二层循环参考两数求和的逻辑。
思路3:先排序后查找,时间复杂度 O(n*n)

- class Solution {
- public static List<List<Integer>> threeSum(int[] nums) {
- List<List<Integer>> list = new ArrayList();
- int len = nums.length;
- if(nums == null || len < 3) return list;
- Arrays.sort(nums); // 排序
- for (int i = 0; i < len ; i++) {
- if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
- if(i > 0 && nums[i] == nums[i-1]) continue; // 则说明该数字重复,会导致结果重复,所以应该跳过
- int L = i+1;//指针从第二个数开始移动
- int R = len-1;
- while(L < R){
- int sum = nums[i] + nums[L] + nums[R];
- if(sum == 0){
- list.add(Arrays.asList(nums[i],nums[L],nums[R]));
- while (L<R && nums[L] == nums[L+1]) L++; // 则会导致结果重复,应该跳过
- while (L<R && nums[R] == nums[R-1]) R--; // 则会导致结果重复,应该跳过
- L++;
- R--;
- }
- else if (sum < 0) L++;
- else if (sum > 0) R--;
- }
- }
- return list;
- }
- }
求数组的第k小,数字数量非常多。
每组数据给出n m k表示有n个数,求第k小,数组的数字由以下规则得到:
ai = mi mod (109+7), i = 1, 2, ..., n
其中 1 ≤ n, m ≤ 5 × 107, 1 ≤ k ≤ n,数据保证得到的数组元素大部分互不相等。
输出第k小的数
3 2 2
4
先复习下快速排序的实现
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- const int mod = 1e9 + 7;
- const int maxn = 1e8 + 10;
- int n, m, k;
- int a[maxn];
- int GetK(int left, int right, int k)
- {
- if(left == right - 1) return a[left];
- int low = left, high = right - 1, center = a[low];
- while(low < high)
- {
- while(low < high && a[high] >= center) high --;
- a[low] = a[high];
- while(low < high && a[low] <= center) low ++;
- a[high] = a[low];
- }
- a[low] = center;
- if(low - left >= k) return GetK(left, low, k);
- else if(low - left + 1 == k) return a[low];
- else return GetK(low + 1, right, k - (low - left) - 1);
- }
- int main()
- {
- while(scanf("%d%d%d", &n, &m, &k) != EOF)
- {
- a[0] = m;
- for(int i = 1; i < n; i ++)
- a[i] = 1LL * a[i - 1] * m % mod;
- printf("%d\n", GetK(0, n, k));
- }
- return 0;
- }
给你一个混合字符串 s ,请你返回 s 中 第二大 的数字,如果不存在第二大的数字,请你返回 -1 。
混合字符串 由小写英文字母和数字组成。
示例 1:
输入:s = "dfa12321afd"
输出:2
解释:出现在 s 中的数字包括 [1, 2, 3] 。第二大的数字是 2 。
示例 2:
输入:s = "abc1111"
输出:-1
解释:出现在 s 中的数字只包含 [1] 。没有第二大的数字。
提示:
1 <= s.length <= 500
s 只包含小写英文字母和(或)数字。
思路:
此题比较简单,直接遍历,用两个变量记录第1大和第2大的数即可。