1、ArrayList数据结构
力控1
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
class Solution {
public int[] twoSum(int[] nums, int target) {
Map
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
利口7
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
if (rev < Integer.MIN_VALUE / 10 || rev > Integer.MAX_VALUE / 10) {
return 0;
}
int digit = x % 10;
x /= 10;
rev = rev * 10 + digit;
}
return rev;
}
}
class Solution {
Map
put(‘I’, 1);
put(‘V’, 5);
put(‘X’, 10);
put(‘L’, 50);
put(‘C’, 100);
put(‘D’, 500);
put(‘M’, 1000);
}};
利口13
class Solution {
Map
put(‘I’, 1);
put(‘V’, 5);
put(‘X’, 10);
put(‘L’, 50);
put(‘C’, 100);
put(‘D’, 500);
put(‘M’, 1000);
}};
public int romanToInt(String s) {<br /> int ans = 0;<br /> int n = s.length();<br /> for (int i = 0; i < n; ++i) {<br /> int value = symbolValues.get(s.charAt(i));<br /> if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {<br /> ans -= value;<br /> } else {<br /> ans += value;<br /> }<br /> }<br /> return ans;<br /> }<br />}
class Solution {public int romanToInt(String s) {s = s.replace("IV","a");s = s.replace("IX","b");s = s.replace("XL","c");s = s.replace("XC","d");s = s.replace("CD","e");s = s.replace("CM","f");int result = 0;for (int i=0; i<s.length(); i++) {result += which(s.charAt(i));}return result;}public int which(char ch) {switch(ch) {case 'I': return 1;case 'V': return 5;case 'X': return 10;case 'L': return 50;case 'C': return 100;case 'D': return 500;case 'M': return 1000;case 'a': return 4;case 'b': return 9;case 'c': return 40;case 'd': return 90;case 'e': return 400;case 'f': return 900;}return 0;}}
public int[] intersect(int[] nums1, int[] nums2) {
// 先对两个数组进行排序
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
List
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
// 如果i指向的值小于j指向的值,,说明i指向
// 的值小了,i往后移一步
i++;
} else if (nums1[i] > nums2[j]) {
// 如果i指向的值大于j指向的值,说明j指向的值
// 小了,j往后移一步
j++;
} else {
// 如果i和j指向的值相同,说明这两个值是重复的,
// 把他加入到集合list中,然后i和j同时都往后移一步
list.add(nums1[i]);
i++;
j++;
}
}
//把list转化为数组
int index = 0;
int[] res = new int[list.size()];
for (int k = 0; k < list.size(); k++) {
res[index++] = list.get(k);
}
return res;
}
