File tree Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Original file line number Diff line number Diff line change
1
+ int search (vector<int >& nums, int target) {
2
+ int len = nums.size ();
3
+ int i = 0 , j = len-1 ;
4
+ while (i < j)
5
+ {
6
+ int mid = (i+j)/2 ;
7
+ if (nums[mid] == target)
8
+ return mid;
9
+ else if (nums[mid] < target)
10
+ i = mid+1 ;
11
+ else
12
+ j = mid-1 ;
13
+ }
14
+
15
+ if (nums[i] == target)
16
+ return i;
17
+ else
18
+ return -1 ;
19
+ }
Original file line number Diff line number Diff line change
1
+ int pivotIndex (vector<int >& nums) {
2
+ int len = nums.size ();
3
+ if (len <= 1 )
4
+ return len-1 ;
5
+ if (len == 2 )
6
+ {
7
+ if (nums[1 ] == 0 )
8
+ return 0 ;
9
+ else if (nums[0 ] == 0 )
10
+ return 1 ;
11
+ else
12
+ return -1 ;
13
+ }
14
+
15
+ vector<int > subsum (len, 0 );
16
+ int sum = 0 ;
17
+ for (int i = 0 ; i < len; ++i)
18
+ {
19
+ sum += nums[i];
20
+ subsum[i] = sum;
21
+ }
22
+
23
+ if (sum-nums[0 ] == 0 )
24
+ return 0 ;
25
+ for (int i = 0 ; i < len-1 ; ++i)
26
+ {
27
+ if (subsum[i] == sum-subsum[i+1 ])
28
+ return i+1 ;
29
+ }
30
+
31
+ return -1 ;
32
+ }
Original file line number Diff line number Diff line change
1
+ bool buddyStrings (string A, string B) {
2
+ int len1 = A.size ();
3
+ int len2 = B.size ();
4
+ if (len1 != len2)
5
+ return false ;
6
+ if (len1 < 2 )
7
+ return false ;
8
+ if (A == B)
9
+ {
10
+ array<int , 26 > arr = {0 };
11
+ if (len1 > 26 )
12
+ return true ;
13
+ for (int i = 0 ; i < len1; ++i)
14
+ {
15
+ arr[A[i]-' a' ]++;
16
+ if (arr[A[i]-' a' ] > 1 )
17
+ return true ;
18
+ }
19
+ return false ;
20
+ }
21
+ char a, b;
22
+ int ct = 0 ;
23
+ for (int i = 0 ; i < len1; ++i)
24
+ {
25
+ if (A[i] != B[i])
26
+ {
27
+ if (ct == 0 )
28
+ {
29
+ a = A[i];
30
+ b = B[i];
31
+ ++ct;
32
+ }
33
+ else if (ct == 1 )
34
+ {
35
+ if (a != B[i] || b != A[i])
36
+ return false ;
37
+ else
38
+ ++ct;
39
+ }
40
+ else
41
+ return false ;
42
+ }
43
+ }
44
+
45
+ return true ;
46
+ }
You can’t perform that action at this time.
0 commit comments