File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.
2
+
3
+ Return the positive integer k. If there is no such integer, return -1.
4
+
5
+ Brute: TC:O(n^2) SC:O(1)
6
+ int maximumNumber=-1;
7
+ for(int i=0; i<nums.size(); i++){
8
+ for(int j=0; j<nums.size(); j++){
9
+ if(nums[i]==-nums[j]){
10
+ maximumNumber=max(maximumNumber, abs(nums[i]));
11
+ }
12
+ }
13
+ }
14
+ return maximumNumber;
15
+
16
+
17
+
18
+ // TC: O(nlogn)+O(n) SC:O(1)
19
+ sort(nums.begin(), nums.end());
20
+
21
+ int i=0, j=nums.size()-1;
22
+
23
+ while(i<j){
24
+ if(nums[i]>0) break;
25
+ if(abs(nums[i])==nums[j]) {
26
+ maximumNumber=max(maximumNumber, abs(nums[i]));
27
+ i++;
28
+ j--;
29
+ }
30
+
31
+ else if(abs(nums[i])<nums[j]){
32
+ j--;
33
+ }
34
+ else{
35
+ i++;
36
+ }
37
+ }
38
+
39
+ return maximumNumber;
40
+
You can’t perform that action at this time.
0 commit comments