Lintcode 143. Sort Colors II

題目鏈接:https://www.lintcode.com/problem/sort-colors-ii/description

最近在刷一下go語言,寫一些go的解法:

/**
 * @param colors: A list of integer
 * @param k: An integer
 * @return: nothing
 */
func sortColors2(colors *[]int, k int) {
	// write your code here
	var length int = len(*colors);
	if (colors == nil || length == 0) {
		return;
	}
	rainbowSort(colors, 0, length-1, 1, k);
}

func rainbowSort(colors *[]int, left int, right int, colorFrom int, colorTo int) {
	if colorFrom == colorTo {
		return;
	}

	if left >= right {
		return;
	}

	var colorMid int = (colorFrom + colorTo) / 2;
	var l int = left;
	var r int = right;
	for {
		if l > r {
			break;
		}
		for {
			if !(l <= r && (*colors)[l] <= colorMid) {
				break;
			}
			l++;
		}
		for {
			if !(l <= r && (*colors)[r] > colorMid) {
				break;
			}
			r--;
		}
		if l <= r {
			var temp int = (*colors)[l];
			(*colors)[l] = (*colors)[r];
			(*colors)[r] = temp;
			l++;
			r--;
		}
	}

	rainbowSort(colors, left, r, colorFrom, colorMid);
	rainbowSort(colors, l, right, colorMid+1, colorTo);
}

func main() {
	fmt.Println("lintcode");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章