统计位数为偶数的数字https://leetcode-cn.com/problems/find-numbers-with-even-number-of-digits/
简单遍历一般,将数位计数,偶数加一,最后输出结果。
int findNumbers(int* nums, int numsSize){
int count = 0, ans = 0;
int i;
for(i = 0; i < numsSize; ++i){
int tmp = nums[i];
while(tmp){
tmp /= 10;
count++;//数位计数
}
if(count % 2 == 0){
ans++;//数位为偶数结果加一
}
count = 0;
}
return ans;
}
有序数组中的单一元素https://leetcode-cn.com/problems/single-element-in-a-sorted-array/
双指针二分查找法
int singleNonDuplicate(int* nums, int numsSize){
int l = 0, r = numsSize - 1;
while(l < r){
int mid = l + (r - l)/2;
if(mid % 2 == 1)mid--;
if(nums[mid] == nums[mid+1]){
l= mid + 2;
} else{
r = mid;
}
}
return nums[l];
}
暴力解法
int singleNonDuplicate(int* nums, int numsSize){
for(int i = 0; i < numsSize - 1; i += 2){
if(nums[i] != nums[i+1]){
return nums[i];
}
}
return nums[numsSize-1];
}
双指针
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* exchange(int* nums, int numsSize, int* returnSize){
int left = 0, right = numsSize - 1;
*returnSize = numsSize;
while(left < right){
while(left < numsSize && nums[left] % 2 == 1){
left++;
}
while(right>=0 && nums[right] % 2 == 0){
right--;
}
if(left>= right){
break;
}
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
left++;
right--;
}
return nums;
}