文章目錄
350.Intersection of Two Arrays II
Problem Description
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Solution Method
題目意思理解錯了,之前以爲交集是連續的。
void Partition(int *nums,int low, int high)
{
if(high>low)
{
int pivotpos=QuickSort(nums,low,high);
Partition(nums,pivotpos+1,high);
Partition(nums,low,pivotpos-1);
}
}
int QuickSort(int *nums,int low,int high)
{
int pivot=nums[low];
while(high>low)
{
while(high>low&&nums[high]>=pivot)high--;
nums[low]=nums[high];
while(high>low&&nums[low]<=pivot)low++;
nums[high]=nums[low];
}
nums[low]=pivot;
return high;
}
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
int * resArr = (int *) malloc (sizeof (int) * (nums1Size + 1));
Partition(nums1, 0, nums1Size - 1);
Partition(nums2, 0, nums2Size - 1);
int sub1 = 0, sub2 = 0, sub = 0;
while (sub1 < nums1Size && sub2 < nums2Size)
{
if (nums1[sub1] == nums2[sub2])
{
resArr[sub ++] = nums1[sub1];
sub1 ++; sub2 ++;
}
else if (nums1[sub1] < nums2[sub2])
sub1 ++;
else if (nums1[sub1] > nums2[sub2])
sub2 ++;
}
*returnSize = sub;
return resArr;
}
367. Valid Perfect Square
Problem Description
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
Solution Method
binary Search
bool isPerfectSquare(int num)
{
long left = 1, right = num;
if (num == 1)
return true;
while (left <= right)
{
long mid = (left + right) / 2;
if (mid * mid == num)
return true;
else if (mid * mid > num)
right = mid - 1;
else if (mid * mid < num)
left = mid + 1;
}
return false;
}