Baidu written test-01 number of exchanges for sequential sequencing

Source: Internet
Author: User

Problem Description:


Problem Analysis:

Solution One: Set the double pointer, start,end; when data[start]= ' 1 ', data[end]= ' 0 ', indicates the need to exchange, the number of times plus 1; otherwise data[end]= ' 1 ' will move the end pointer forward; Data[start]= ' 0 ' Moves the start pointer back;

The algorithm only needs to traverse once

Solution Two: First to calculate the number of characters in the array of 0 zero, and then calculate the number of the first zero character 1, that is, to exchange to the back of the character (only need to traverse to zero characters);

Code:

Solution One:

Import Java.util.scanner;public class Main1 {public static void main (string[] args) {Scanner in = new Scanner (system.in); /record How many sets of data int data_length = In.nextint ();//First layer loop for (int i = 0; i < data_length; i++) {String str = in.next (); char[] Cha rs = Str.tochararray (); int start = 0;int end = Chars.length-1;int result = 0;while (Start < end) {if (chars[start] = = ' 1 ' && chars[end] = = ' 0 ') {++result;start ++;end--;} else {if (chars[end] = = ' 1 ') {end--;} if (chars[start] = = ' 0 ') {start + +;}}} SYSTEM.OUT.PRINTLN (result);}}}

Solution Two: Import Java.util.scanner;public class Main1 {public static void main (String args[]) {Scanner in = new Scanner (system.i n); int n = In.nextint (); while (n--! = 0) {int zero = 0, swap = 0; String str = In.next (); for (int i = 0; i < str.length (); i++) if (Str.charat (i) = = ' 0 ') zero++;for (int i = 0; i < Zer O i++) if (Str.charat (i) = = ' 1 ') swap++; SYSTEM.OUT.PRINTLN (Swap);}}}


Baidu written test-01 number of exchanges for sequential sequencing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.