13调整奇数顺序使奇数在前偶数在后

 1 //调整奇数顺序使奇数在前偶数在后
 2 //题目:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,
 3 //使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,
 4 //并保证奇数和奇数,偶数和偶数之间的相对位置不变。
 5 ///思路: 1 2 3 4 5 6 7  先建立一个新的容器,遇到偶数就存放到新的容器且将其从旧数组中删除,
 6 //然后再将新数组加入到旧数组中
 7 //--------------奇数放在前面,偶数放在后面,但是考虑相对位置---------------
 8 class Solution
 9 {
10 public:
11     void reOrderArray(vector<int> & array)
12     {
13         int size = array.size();
14         if (size <= 0)
15         {
16             return ;
17         }
18         vector<int> tmpArray;
19         vector<int>::iterator first = array.begin();
20         vector<int>::iterator last = array.end();
21         while(first != array.end())
22         {
23             if ((*first & 1) == 0)
24             {
25                 tmpArray.push_back(*first);
26                 first = array.erase(first);
27             }
28             else
29             {
30                 first++;
31             }
32         }
33         vector<int>::iterator tmpFirst = tmpArray.begin();
34         vector<int>::iterator tmpLast = tmpArray.end();
35         while(tmpFirst != tmpArray.end())
36         {
37             array.push_back(*tmpFirst);
38             first = tmpArray.erase(tmpFirst);
39         }
40     }
41 };
42 
43 //--------------奇数放在前面,偶数放在后面,但是不考虑相对位置---------------
44 class Solution 
45 {
46 public:
47     void reOrderArray(vector<int> &array) 
48     {
49         //鲁棒性
50         int length = array.size();
51         if (length <=0 )
52         {
53             return;
54         }
55         //定义前后索引
56         int arrayStart = 0;
57         int arrayEnd = length-1;
58         int tmp;
59         while(arrayStart < arrayEnd)
60         {
61             //奇数位置保持不变,继续向右查找
62            if (arrayStart < arrayEnd &&(array[arrayStart] & 0x1) != 0)
63            {
64                arrayStart++;
65            }
66            //偶数位置保持不变,继续向左查找
67            if (arrayStart < arrayEnd &&(array[arrayEnd] & 0x1) == 0)
68            {
69                arrayEnd--;
70            }
71            //当发现前者不是奇数,后者不是偶数,则交换位置
72            if (arrayStart < arrayEnd)
73            {
74                tmp = array[arrayStart];
75                array[arrayStart] = array[arrayEnd];
76                array[arrayEnd] = tmp;
77            }
78         }
79     }
80 };

 

posted @ 2017-08-20 20:29  繁星的夜空2012  阅读(225)  评论(0)    收藏  举报