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
- 16.11.11
- 苏嵌11 16.11.10
- 苏嵌12 16.11.11
- 16.11.1
- 16.11.2
- 16.11.3
- 16.11.4
- 16.11.5
- 16.11.7
- 16.11.8
- 16.11.9
- 16.11.10
- 16.11.12
- 16.11.24
- 16.11.25
- 16.11.28
- 16.11.29
- 苏嵌3 16.11.1
- 【BZOJ 1047】 [HAOI2007]理想的正方形 单调队列(也可以dp水)
- 【HTML5】选择列表及文本框
- 面试宝典(三)
- 时间序列(arima)+支持向量机(svm)+优化=组合预测
- Tomcat server.xml配置
- 16.11.11
- Spring_aop学习
- oninput和onpropertychange以及其兼容处理
- dependencyManagement与dependencies的区别
- 剑指offer 面试题6 重建二叉树 java版答案
- 程序员为什么要学深度学习?
- spark sql中的sqlcontext与hivecontext区别
- UML类图几种关系的总结
- 欢迎使用CSDN-markdown编辑器