-
Notifications
You must be signed in to change notification settings - Fork 5
/
SuccessfulPairsOfSpellsAndPotions.java
64 lines (62 loc) · 2.13 KB
/
SuccessfulPairsOfSpellsAndPotions.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*https://leetcode.com/problems/successful-pairs-of-spells-and-potions/*/
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
Arrays.sort(potions);
int s, low, high, mid, sLen = spells.length, pLen = potions.length, p = -1;
int[] result = new int[sLen];
for (s = 0; s < sLen; ++s)
{
if ((long)spells[s]*(long)potions[0] >= success) result[s] = pLen;
else if ((long)spells[s]*(long)potions[pLen-1] < success) result[s] = 0;
else
{
low = 0;
high = pLen-1;
while (low <= high)
{
mid = low+(high-low)/2;
if ((long)spells[s]*(long)potions[mid] >= success)
{
p = mid;
high = mid-1;
}
else low = mid+1;
}
result[s] = pLen-p;
}
}
return result;
}
}
class Solution {
public int[] successfulPairs(int[] spell, int[] potion, long success) {
int i, s, low, high, mid, sLen = spell.length, pLen = potion.length, p = -1;
long[] spells = new long[sLen], potions = new long[pLen];
for (i = 0; i < sLen; ++i) spells[i] = (long)spell[i];
for (i = 0; i < pLen; ++i) potions[i] = (long)potion[i];
Arrays.sort(potions);
int[] result = new int[sLen];
for (s = 0; s < sLen; ++s)
{
if (spells[s]*potions[0] >= success) result[s] = pLen;
else if (spells[s]*potions[pLen-1] < success) result[s] = 0;
else
{
low = 0;
high = pLen-1;
while (low <= high)
{
mid = low+(high-low)/2;
if (spells[s]*potions[mid] >= success)
{
p = mid;
high = mid-1;
}
else low = mid+1;
}
result[s] = pLen-p;
}
}
return result;
}
}