有时间就刷两道算法题
1.Two sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].题意大概就是给一个Int数组, 给一个结果值, 输出两两相加为结果值的数字。
以下为我的解法:
public void twoSum(int[] nums, int target) { int num = nums.length; for (int i = 0; i < num; i++) { int a = nums[i]; for (int j = i + 1; j < num; j++) { int b = nums[j]; if ((a + b) == target) { Log.d(TAG,a + " "+b); } } } }
2.Count and say
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
题目大意为
“1”开始,1读作1个1,因此输出“11”
“11”读作2个1,因此输出“21”
“21”读作1个2,1个1,因此输出“1211”
依次类推
以下为我的答案,跟网上的大神对比,我的逻辑比较复杂,效率较低,但我还是把它记录下来,因为是第一反应下写出的逻辑
private void getInterger(int n) { String a = "1"; String outputString = ""; for (int i = 0; i < n; i++) { outputString = ""; int num = a.length(); Log.d(TAG, "a: "+a); String b = ""; String c = ""; int k = 1; if (num == 1) { outputString = "11"; a = outputString; continue; } for (int j = 0; j < num; j++) { b = a.substring(j,j+1); if (j+2 > num) { if (b.equals(c)) { outputString = outputString+k+b; }else { outputString = outputString + "1"+b; } a = outputString; continue; } c = a.substring(j+1,j+2); if (b.equals(c)) { k++; }else { outputString = outputString+k+b; k = 1; } } } Log.d(TAG, "getInterger: " + outputString); }