Fork me on GitHub

1147. 递减元素使数组呈锯齿状

class Solution {
	public int movesToMakeZigzag(int[] nums) {
	int temp1[] = new int[nums.length];
			int temp2[] = new int[nums.length];
			for (int i = 0; i < nums.length; i++) {
				temp1[i] = nums[i];
				temp2[i] = nums[i];
			}
			int ans1 = 0;
			int ans2 = 0;
			for (int i = 1; i < temp1.length; i+=2) { //两边小 中间大  
				if (temp1[i - 1] >= temp1[i]) {
					ans1 += temp1[i - 1] - temp1[i] + 1; 
					temp1[i - 1] = temp1[i] - 1;
				}

				if (i + 1 < temp1.length && temp1[i + 1] >= temp1[i]) {
					ans1 += temp1[i + 1] - temp1[i] + 1;
					temp1[i + 1] = temp1[i] - 1;
				}
			}

			for (int i = 1; i < temp2.length; i+=2) { //两边小,中间大
				if (temp2[i - 1] <= temp2[i]) {
					ans2 += temp2[i] - temp2[i - 1] + 1;
					temp2[i] = temp2[i - 1] - 1;
				}
				if (i + 1 < temp2.length && temp2[i + 1] <= temp2[i]) {
					ans2 += temp2[i] - temp2[i + 1] + 1;
					temp2[i] = temp2[i + 1] - 1;
				}
			}
			return ans1 <= ans2 ? ans1 : ans2;
		}
}
posted @ 2019-08-04 15:04  cznczai  阅读(294)  评论(0编辑  收藏  举报