16.11.11

来源:互联网 发布:a站 b站 知乎 编辑:程序博客网 时间:2024/06/03 11:04

349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
分析:查找两个数组中的交集(利用set)

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set<Integer> set = new HashSet<Integer>();        Set<Integer> resultSet = new HashSet<Integer>();        int count=0;        //将nums1存入HashSet中        for(int i=0;i<nums1.length;i++){            set.add(nums1[i]);        }        //遍历nums2,当set中存在,则将重复元素存入resultSet        for(int i=0;i<nums2.length;i++){            if(set.contains(nums2[i])){                resultSet.add(nums2[i]);            }        }        //遍历取出resultSet中的元素并存入数组中        Iterator<Integer> iterator = resultSet.iterator();        int[] result=new int[resultSet.size()];        while(iterator.hasNext()){            result[count++]=iterator.next();        }        return result;    }}

345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1: Given s = “hello”, return “holle”.
Example 2: Given s = “leetcode”, return “leotcede”.
分析:该题目的意思是反转一个字符串中的元音字母。将这个字符串中的第一个和最后一个元音字母交换,第二个和倒数第二个交换…

public class Solution {    public String reverseVowels(String s) {        //将元音字母存放在集合中        Set<Character> set = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));        char[] charArray = s.toCharArray();        int left=0,right=s.length()-1;        while(left<right){            //判断当前字母是否为元音字母,不是则向后移动            if(!set.contains(charArray[left])){                left++;            }else if(!set.contains(charArray[right])){                right--;            //否则将两个元音字母交换位置,并且移动指针            }else{                char temp=charArray[left];                charArray[left]=charArray[right];                charArray[right]=temp;                left++;                right--;            }        }        //返回新生成的字符串        return new String(charArray);    }}

344. Reverse String

Write a function that takes a string as input and returns the string reversed.
Example: Given s = “hello”, return “olleh”.
分析:将字符串逆序

public class Solution {    public String reverseString(String s) {      int n=s.length();      char[] res=new char[n];      char[] ori=s.toCharArray();      //创建新的字符串,逆序遍历旧字符串并存放      for(int i=0,j=n-1;i<n;i++,j--){          res[i]=ori[j];      }      return new String(res);    }}
0 0