赞
踩
题目:把一个只包含01的字符串 进行排序,问最少可以交换多少次?
1,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1
解题思路:利用快排思想 左边i 右边j 左边遇到1 右边遇到0 时交换 并计数一次 直到i=j位置
- public class zerooneswitch {
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int a[]={1,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1};
-
- System.out.println(zerooneswitch(a, 0, a.length-1));
- }
- public static int zerooneswitch(int a[],int left,int right)
- {
- int n = 0;
- int temp;
- while(left<right)//循环前提条件
- {
- while(left<right&&a[left]==0)//左边遇到1之前 向右移位
- left++;
- while(left<right&&a[right]==1)//右边遇到0之前 向左移位
- right--;
- if(left<right) //交换并计数
- {
- temp=a[left];
- a[left]=a[right];
- a[right]=temp;
- n++;
- }
-
- }
- return n;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。