代码随想录算法训练营第一天 | LeetCode704二分查找、27移除元素

第一天的题之前做过了,在此简写。

704 二分查找

#include 
#include 
#include 
#include 
#include 


using  namespace std;

int search(vector& nums, int target)
{
	int left = 0;
	int right = nums.size() - 1;
	while (nums[left] < nums[right])
	{
		int middle = left + (right - left) / 2;
		if (target < nums[middle])
		{
			right = middle-1;
		}
		else if (target > nums[middle])
		{
			left = middle+1;
		}
		else
		{
			return middle;
		}

	}
	return -1;
}
int main()
{
	vector wzh;
	for (int i = 42; i <= 80; i++)
	{
		wzh.push_back(i);

	}
	int map = 50;
	int a = search(wzh, map);
	cout << a << endl;
	return 0;
}

 27.移除元素

#include 
#include 
#include 
#include 
#include 


using  namespace std;

int removeElement(vector& nums, int val) {
	int slowIndex = 0;
	for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
		if (val != nums[fastIndex]) {
			nums[slowIndex++] = nums[fastIndex];
		}
	}
	return slowIndex;
}
int search(vector& nums, int target)
{
	int slowindex = 0;
	int size = nums.size();
	for (int fastindex = 0; fastindex < nums.size(); fastindex++)
	{
		if (  nums[fastindex] != target)
		{
			nums[slowindex] = nums[fastindex];
			slowindex++;
		}
	}
	return slowindex;
}
int main()
{
	vector wzh;
	for (int i = 42; i <= 80; i++)
	{
		wzh.push_back(i);

	}
	int map = 50;
	int a = search(wzh, map);
	cout << a << endl;
	return 0;
}

最初的算法题逻辑简单但是写起来总是细节上出现错误,大概是之前很少手敲代码,都是调试改动别人的代码的原因。

你可能感兴趣的:(代码随想录打卡,leetcode,算法,数据结构)