LeetCode 204. Count Primes
int countPrimes(int n) {
vector notPrime(n, 0);
int count = 0;
for(int i = 2; i < n; i++) {
if(!notPrime[i]) {
count++;
for(int j = 2; i*j < n; j++)
notPrime[i*j] = 1;
}
}
return count;
}
思路:利用乘积的原理,除去合数,注意比起使用 vector
LeetCode 1.Two Sum
vector twoSum(vector& nums, int target) {
int len = nums.size();
unordered_map m;
vector res;
for(int i = 0; i < len; i++) {
int complement = target-nums[i];
auto iter = m.find(complement);
if(iter == m.end())
m.insert(pair(nums[i], i));
else
res = vector{iter->second, i};
}
return res;
}
思路:使用unordered_map,本质上还是hash表。
LeetCode 167. Two Sum II - Input array is sorted
int BinarySearch(vector & numbers, int target) {
int left = 0, right = numbers.size()-1;
while(left <= right) {
int mid = (left + right) / 2;
if(numbers[mid] > target)
right = mid-1;
else
left = mid+1;
}
if(right >= 0 && numbers[right] == target)
return right;
return -1;
}
vector twoSum(vector& numbers, int target) {
vector res;
int len = numbers.size();
for(int i = 0; i < len; i++) {
int tmp = BinarySearch(numbers, target-numbers[i]);
if(tmp == -1 || tmp == i) continue;
res = vector{i+1, tmp+1};
break;
}
return res;
}
思路:既然排好序,就用二分查找吧,上一道题的思路也可行,注意这次的index从一开始,邪教emmm
LeetCode 15. 3Sum
vector > threeSum(vector& nums) {
int len = nums.size();
vector > res;
sort(nums.begin(), nums.end());
for(int i = 0; i < len; i++) {
int target = -nums[i];
int front = i + 1;
int back = len - 1;
if(target < 0) break;
while(front < back) {
int sum = nums[front] + nums[back];
if(sum < target)
front++;
else if(sum > target)
back--;
else {
vector vec{nums[i], nums[front], nums[back]};
res.push_back(vec);
while(front < back && nums[front] == vec[1]) front++;
while(front < back && nums[back] == vec[2]) back--;
}
}
while(i+1 < len && nums[i+1] == nums[i]) i++;
}
return res;
}