压缩字符串比如fffff压缩成5f
预判断下一个字符是否与前一个相等,如果相等则进行计数,不等则直接放到新的数组中,注意判断计数值是否大于1来判断是否字符重复。还要记得将计数器的值还原
public String compressChar(char[] a)
{
if(a==null||a.length==1)
{
return a.toString();
}
int count=1;
StringBuilder stringBuilder=new StringBuilder();
for(int i=0;i<a.length;i++)
{
if((i+1)<a.length&&a[i+1]==a[i])
{
count++;
continue;
}else {
if(count>1){
stringBuilder.append(count);
count=1;
stringBuilder.append(a[i]);
}
}
}
return stringBuilder.toString();
}
寻找两个和为定值的数
假设数组有序(假设升序),可以不断逼近,头尾两个指针所指的数如果和大于给定的值,则tail–,小于给定的值则head++
public void twoSum(int[] a,int value)
{
int head=0;
int tail=a.length-1;
while (head<tail)
{
if(a[head]+a[tail]>value)
{
tail--;
}
if(a[head]+a[tail]<value)
{
head++;
}else {
System.out.println(a[head]+"+"+a[tail]+"="+value);
return;
}
}
System.out.println("can't find two sum");
}
该题还可以考虑用空间换时间,用hash表存储数值,从头取数,查看对应的能让和等于给定值得数是否在hash表中
如果要找出所有的这样的两个数
public void twoSum(int[] a,int value)
{
int head=0;
int tail=a.length-1;
int flag=0;
while (head<tail)
{
if(a[head]+a[tail]>value)
{
tail--;
}
if(a[head]+a[tail]<value)
{
head++;
}else {
flag=1;
System.out.println(a[head]+"+"+a[tail]+"="+value);
head++;
tail--;
}
}
if(flag==0)
{
System.out.println("can't find two sum");
}
}
java中hashmap快速遍历的方式
//效率最高
Map<String,Integer> map=new HashMap<>();
map.put("one",1);
map.put("two",2);
map.put("three",3);
map.put("four",4);
Iterator iterator=map.entrySet().iterator();
while (iterator.hasNext())
{
Map.Entry entry=(Map.Entry)iterator.next();
String key= (String) entry.getKey();
int value= (int) entry.getValue();
System.out.println(key);
}
和为s的连续正数序列
- 从1开始遍历以i为基准,每次加上i++的值,如果resultsum
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> result=new ArrayList<>();
if(sum<=0)
{
return result;
}
for(int i=1;i<=sum>>1;i++)
{
ArrayList<Integer> item=new ArrayList<>();
int j=i;
int resultsum=0;
while (resultsum<sum){
resultsum+=j;
item.add(j);
j++;
}
if(resultsum==sum)
{
result.add(item);
}
}
return result;
}
2.使用两个指针,先让star=1,end=2.如果resultsum
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum)
{
vector<vector<int> > res;
if(sum < 3) return res;
int mid = (sum + 1)>>1;
int begin = 1;
int end = 2;
int cur = begin + end;
while(begin < mid && end < sum)
{
while(cur > sum)
{
cur -= begin;
begin++;
}
if(cur == sum)
InsertRes(begin,end,res);
end++;
cur += end;
}
return res;
}
void InsertRes(int begin,int end,vector<vector<int> > &res)
{
vector<int> temp;
for(int i = begin;i<=end;i++)
temp.push_back(i);
res.push_back(temp);
}
};