775.全局倒置与局部倒置

超时解法1:

class Solution {
public:
	bool isIdealPermutation(vector<int>& A) 
	{
		map<int, vector<int>>count;
		/*局部倒置*/
		int Local = 0;
		for (int i = 0; i <A.size(); i++)
		{
			if (i < A.size() - 1)
				if (A[i] > A[i + 1])
					Local++;
			//count[A[i]].push_back(0);
			count[A[i]].push_back(i);
		}
		/*全局倒置*/
		int Global = 0;
		for (auto i = count.begin(); i !=count.end(); i++)
		{
			pair<int, vector<int>>te1 = *i;
			for (auto j = count.begin(); j != count.end(); j++)
			{
				pair<int, vector<int>>te2 = *j;
				if (te2.first < te1.first)
				{
					Global += numbers(te1.second, te2.second);
				}
				else
					break;
			}
		}
		if (Global == Local)
			return true;
		return false;
	}
	int numbers(vector<int>information, vector<int>target)
	{
		int ans = 0;
		if (target.size()==1)
		{
			for (int i = 0; i < information.size(); i++)
			{
				if (information[i] < target[0])
					ans++;
			}
			
		}
		else
			for (int i = 0; i < information.size(); i++)
			{
				int te = information[i];
				for (int j = 0; j < target.size(); j++)
				{
					if (target[j] > te)
					{
						ans += target.size() - j;
						break;
					}
				}
			}
		return ans;
	}
};

超时解法2:

class Solution {
public:
	bool isIdealPermutation(vector<int>& A) {
		for (auto i = A.begin(); i < A.end() - 1; i++)
		{
			if (i + 2 != A.end() && *i > *min_element(i + 2, A.end()))
				return false;
		}
		return true;
	}
};

正确解法:
思路:根据题目要求,数组里的数不存在重复元素,并且,只要是局部倒置就一定是全局倒置,反过来,全局倒置不一定是局部倒置,所有想要全局倒置等于局部倒置,有且仅有一种情况下才可能返回TRUE;那就是所有的全局倒置都是局部倒置:J有且仅有一个值就是I+1;

class Solution {
public:
	bool isIdealPermutation(vector<int>& A) 
	{
		for (int i = 0; i < A.size(); i++)
		{
			if (abs(A[i] - i) > 1)
				return false;
		}
		return true;
	}
};```

猜你喜欢

转载自blog.csdn.net/kongqingxin12/article/details/84748711