递归解法
class Solution {
public:
int search(vector<int>& nums, int target) {
return midsearch(nums,target,0,nums.size()-1);
}
int midsearch(vector<int>& nums, int target, int low,int high)
{
if(low <= high)
{
int mid = (low+high) / 2;
if(nums[mid]<target) return midsearch(nums,target,mid+1,high);
if(nums[mid]>target) return midsearch(nums,target,low,mid-1);
if(nums[mid] == target) return mid;
}
return -1;
}
};
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0;
int high = nums.size()-1;
while(low<=high)
{
int mid = (low+high) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) high = mid - 1;
else low = mid + 1;
}
return -1;
}
};
class Solution {
public:
bool isAnagram(string s, string t) {
int n1 = s.size();
int n2 = t.size();
if(n1!=n2) return false;
quicksort(s,0,n1-1);
quicksort(t,0,n2-1);
if(s==t) return true;
return false;
}
int partition(string &s ,int low,int high)
{
char c = s[low];
while(low<high)
{
while(low<high && s[high] >= c) high--;
s[low] = s[high];
while(low<high && s[low] <= c) low++;
s[high] = s[low];
}
s[low] = c;
return low;
}
void quicksort(string &s,int low,int high)
{
if(low < high)
{
int p = partition(s,low,high);
quicksort(s,low,p-1);
quicksort(s,p+1,high);
}
}
};
顺便练习一下快排