Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6ea33dc

Browse files
Create 1498. Number of Subsequences That Satisfy the Given Sum Condition
1 parent a4ee98c commit 6ea33dc

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Solution {
2+
public int numSubseq(int[] nums, int target) {
3+
Arrays.sort(nums);
4+
int mod = 1_000_000_007;
5+
int result =0;
6+
int n = nums.length;
7+
int[] power = new int[n];
8+
power[0] = 1;
9+
for(int i=1;i<n;i++){
10+
power[i] = (power[i-1] * 2) % mod;
11+
}
12+
13+
for(int left=0;left<n;left++){
14+
int right = binarySearch(nums,target- nums[left]) - 1;
15+
if(right>=left){
16+
result += power[right - left];
17+
result %= mod;
18+
}
19+
}
20+
21+
return result;
22+
}
23+
24+
private int binarySearch(int[] nums, int value){
25+
int low = 0, high = nums.length - 1;
26+
while(low<=high){
27+
int mid = low + (high - low)/2;
28+
if(nums[mid]<=value){
29+
low = mid + 1;
30+
}
31+
else{
32+
high = mid - 1;
33+
}
34+
}
35+
return low;
36+
}
37+
}
38+
39+
class Solution {
40+
public int numSubseq(int[] nums, int target) {
41+
Arrays.sort(nums);
42+
int mod = 1_000_000_007;
43+
int result =0;
44+
int n = nums.length;
45+
int[] power = new int[n];
46+
power[0] = 1;
47+
for(int i=1;i<n;i++){
48+
power[i] = (power[i-1] * 2) % mod;
49+
}
50+
int left = 0 , right = n - 1;
51+
52+
while(left<=right){
53+
if(nums[left] + nums[right] <= target){
54+
result += power[right - left];
55+
result %= mod;
56+
left++;
57+
}
58+
else{
59+
right--;
60+
}
61+
}
62+
63+
return result;
64+
}
65+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /