package y2019.Algorithm.array;

/**
* @ProjectName: cutter-point
* @Package: y2019.Algorithm.array
* @ClassName: SortArrayByParity
* @Author: xiaof
* @Description: 905. Sort Array By Parity
* Given an array A of non-negative integers, return an array consisting of all the even elements of A,
* followed by all the odd elements of A.
* You may return any answer array that satisfies this condition.
*
* Input: [3,1,2,4]
* Output: [2,4,3,1]
* The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
*
* @Date: 2019/7/3 8:48
* @Version: 1.0
*/
public class SortArrayByParity { public int[] solution(int[] A) {
//先获取所有偶元素,然后获取所有奇元元素,还有一个方法就是交换前后位置
//吧所有偶数放到前面,奇数放后面,类似快排
int index1 = 0, index2 = A.length - 1;
while(index1 < index2) {
//遍历起始第一个不是偶数的位置
while(index1 < A.length && (A[index1] & 1) == 0) {
index1++;
}
//后面往前,找到第一个不是奇数
while(index2 > 0 && (A[index2] & 1) == 1) {
index2--;
}
//交换位置
if(index1 < index2 && index1 < A.length && index2 > 0) {
//交换位置
int temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
}
} return A;
} public static void main(String args[]) {
int A[] = {3,1,2,4};
SortArrayByParity fuc = new SortArrayByParity();
System.out.println(fuc.solution(A));
}
}

最新文章

  1. LightGBM中GBDT的实现
  2. Visual Studio工具——为编辑器增加垂直辅助线
  3. Unity3D多人协作开发环境搭建
  4. d is undefined错误
  5. Orchard Core一分钟搭建ASP.NET Core CMS
  6. 网站开发进阶(三十八)Web前端开发规范文档你需要知道的事
  7. 驰骋工作流引擎 -Webservice接口说明文档
  8. 下载Dynamics 365 Customer Engagement 工具
  9. [CQOI2018]交错序列
  10. setValuesForKeysWithDictionary:的用途
  11. 读取web.config和app.config配置文件
  12. java-学习5
  13. RTSP server 在mips 上莫名其妙退出(PC上则无此问题)
  14. I2C总线信号时序总结【转】
  15. 各大公司java后端开发面试题
  16. 文本处理三剑客之 sed
  17. NDK 链接第三方静态库的方法
  18. Swift3.0字符串大小写转化
  19. 第二次c++作业(觉得渐渐入门系列)
  20. 微信小程序 - 输入起点、终点获取距离并且进行路线规划(腾讯地图)

热门文章

  1. 浏览器端使用less
  2. P4936 题解
  3. Spyder汉化问题
  4. 一次修复linux的efi引导的集中方法总结记录
  5. mysql 根据发音查找内容
  6. var let const区别
  7. 退出状态、测试(test or [])、操作符、[]与[[]]区别
  8. Partition-wise join
  9. Spark资源调度及任务调度
  10. H3C Telnet 配置