Chinaunix首页 | 论坛 | 博客
  • 博客访问: 254191
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-09-11 13:30:46

//Sort Colors Total Accepted: 65124 Total Submissions: 199819 My Submissions Question Solution 
//Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
//
//Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
//
//Note:
//You are not suppose to use the library's sort function for this problem.
public class SortColors {


public static void main(String[] args) {
// TODO Auto-generated method stub


}
public void sortColors(int[] nums) {
        int midindex=quickSort(nums, 0, 0, nums.length-1);
    quickSort(nums, 1, midindex+1, nums.length-1);
  }
   public int quickSort(int[] nums,int middata,int start,int end){
int i=start;
 
for(;i<=end;i++){
if(nums[i]==middata)
break;
}
if(i>end){
return start-1;
}
int temp=nums[i];
nums[i]=nums[start];
i=start;
int j=end;
while(i<j){
while(i<j&&nums[j]>temp)
j--;

nums[i]=nums[j];

while(i<j&&nums[i]<=temp)
i++;

nums[j]=nums[i];


}
nums[i]=temp;
return i;
}
}

使用引用数组作为实参是可以改变生成对象的值,但是无法让两个引用指向的对象发生变化。如下例



class Node1 {
    int val;
    Node1 left=null;
    Node1 right=null;
    Node1(int x) { val = x; }
}
public class SwapObject {


public static void main(String[] args) {
// TODO Auto-generated method stub
int a=3;
int b=2;
swap(a,b);
Node1 node1=new Node1(3);
Node1 node2=new Node1(2);
swap2(node1,node2);
System.out.println(a+" "+b);
System.out.println(node1.val+" "+node2.val);
}
private static void swap2(Node1 node1, Node1 node2) {
// TODO Auto-generated method stub
Node1 temp=node1;
node1=node2;
node2=temp;
node2.val=6;
}
private static void swap(int a, int b) {
// TODO Auto-generated method stub
int temp=a;
a=b;
b=temp;
}

}
结果:
3 2
6 2


阅读(256) | 评论(0) | 转发(0) |
0

上一篇:Edit Distance

下一篇:MinimumWindowSubstring

给主人留下些什么吧!~~